package com.aiyige.page.publish.service;

import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.apiengine.ActionEngine;
import com.aiyige.base.db.dao.InfoModelDao;
import com.aiyige.base.db.dao.LearnVideoModelDao;
import com.aiyige.base.db.dao.MajorCourseDBModelDao;
import com.aiyige.base.db.dao.NormalVideoModelDao;
import com.aiyige.base.db.dao.PhotoModelDao;
import com.aiyige.base.db.dao.SpecialTopicDBModelDao;
import com.aiyige.base.db.dao.TraingCardDBModelDao;
import com.aiyige.base.db.dao.TraingClassDBModelDao;
import com.aiyige.base.db.dao.UploadFileDao;
import com.aiyige.base.db.table.InfoModel;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.base.db.table.MajorCourseDBModel;
import com.aiyige.base.db.table.NormalVideoModel;
import com.aiyige.base.db.table.PhotoModel;
import com.aiyige.base.db.table.SpecialTopicDBModel;
import com.aiyige.base.db.table.TraingCardDBModel;
import com.aiyige.base.db.table.TraingClassDBModel;
import com.aiyige.base.db.table.UploadFile;
import com.aiyige.configs.MyConfig;
import com.aiyige.location.model.LocationData;
import com.aiyige.model.Oss;
import com.aiyige.model.moment.backup.CardBackup;
import com.aiyige.model.moment.backup.CourseBackup;
import com.aiyige.model.moment.backup.DetailBackup;
import com.aiyige.model.moment.backup.TagBackup;
import com.aiyige.model.moment.entity.Article;
import com.aiyige.model.moment.entity.Content;
import com.aiyige.model.moment.entity.Guarantee;
import com.aiyige.model.moment.entity.MajorCourse;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.Photo;
import com.aiyige.model.moment.entity.SinglePhoto;
import com.aiyige.model.moment.entity.SingleVideo;
import com.aiyige.model.moment.entity.TrainingCard;
import com.aiyige.model.moment.entity.TrainingCourse;
import com.aiyige.model.moment.entity.Video;
import com.aiyige.model.moment.entity.VideoCourse;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.util.InterestUtil;
import com.aiyige.page.publish.coursedescription.model.CourseDescriptionModel;
import com.aiyige.page.publish.courseschedule.model.CourseScheduleModel;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.publish.majorcourse.model.ClassLocation;
import com.aiyige.page.publish.majorcourse.model.MajorCourseFormModel;
import com.aiyige.page.publish.majorcourse.model.MajorCourseType;
import com.aiyige.page.publish.selectcourse.model.Course;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.selectlearntarget.model.SelectLearnTargetItem;
import com.aiyige.page.publish.selectsuitablelearnage.model.SuitableLearnAgeItem;
import com.aiyige.page.publish.selectsuitablepeople.model.SelectSuitablePeopleItem;
import com.aiyige.page.publish.selecttag.model.SelectTagItem;
import com.aiyige.page.publish.selecttraingcard.model.TraingCard;
import com.aiyige.page.publish.traingcard.model.TraingCardFormModel;
import com.aiyige.page.publish.traingclass.model.TraingClassFormModel;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.richtexteditor.model.Persistent;
import com.aiyige.richtexteditor.util.RichTextUtil;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ffmpeg.TranscoderUtils;
import com.aiyige.utils.widget.articleview.model.ArticleNode;
import com.alibaba.fastjson.JSON;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.stmt.Where;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.storage.persistent.FileRecorder;
import com.vondear.rxtools.RxFileTool;

import org.json.JSONObject;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber;

public class PublishService extends Service {
    UploadManager uploadManager = null;
    Dao<LearnVideoModel, String> learnVideoModelDao = null;
    Dao<UploadFile, Integer> uploadFileDao = null;
    Dao<PhotoModel, String> photoModelDao = null;
    Dao<InfoModel, String> infoModelDao = null;
    Dao<NormalVideoModel, String> normalVideoModelDao = null;
    ScanThread scanThread;
    Handler mainHandler = null;
    Notification publishServiceNotification;
    public static final int PUBLISH_SERVICE_NOTIFICATION_ID = 1;

    public PublishService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        learnVideoModelDao = LearnVideoModelDao.getDao();
        uploadFileDao = UploadFileDao.getDao();
        photoModelDao = PhotoModelDao.getDao();
        infoModelDao = InfoModelDao.getDao();
        normalVideoModelDao = NormalVideoModelDao.getDao();
        mainHandler = new Handler(Looper.getMainLooper());
        publishServiceNotification = new Notification.Builder(this)
                .setOngoing(true)
                .setTicker(getString(R.string.uploading))
                .setContentTitle(getString(R.string.aiyige_upload_service))
                .setContentText(getString(R.string.uploading))
                .setSmallIcon(R.mipmap.ic_launcher)
                .build();
        //startForeground(PUBLISH_SERVICE_NOTIFICATION_ID, publishServiceNotification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!AccountUtil.isLogin()) {
            stopSelf();
            return START_NOT_STICKY;
        }
        if (uploadManager == null) {
            try {
                FileRecorder recorder = new FileRecorder(MyConfig.QINIU_UPLOAD_CACHE_DIR);
                KeyGenerator keyGen = new KeyGenerator() {
                    public String gen(String key, File file) {
                        return key + "_._" + new StringBuffer(file.getAbsolutePath()).reverse();
                    }
                };
                Configuration configuration = new Configuration.Builder()
                        .chunkSize(512 * 1024)
                        .putThreshhold(1024 * 1024)
                        .connectTimeout(10)
                        .responseTimeout(15)
                        .recorder(recorder, keyGen)
                        .zone(AutoZone.autoZone)
                        .build();
                uploadManager = new UploadManager(configuration);
                scanThread = new ScanThread();
                scanThread.start();
            } catch (Exception e) {
                uploadManager = null;
            }
        }
        return START_STICKY;
    }

    public static void startPublish(Context context) {
        context.startService(new Intent(context, PublishService.class));
    }

    @Override
    public void onDestroy() {
        if (scanThread != null) {
            scanThread.shutdown();
        }
        super.onDestroy();
    }

    public void sendUploadUpdateBroadcast() {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                PublishUtil.sendUploadUpdateBroadcast();
            }
        });
    }

    public void sendProgressStatusUpdateBroadcast() {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                PublishUtil.sendPublishProgressStatusUpdateBroadcast();
            }
        });
    }

    public void sendTranscodeUpdateBroadcast() {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                PublishUtil.sendTranscodeUpdateBroadcast();
            }
        });
    }


    public class ScanThread extends Thread implements TranscoderUtils.TranscoderCallback {
        public final String TAG = ScanThread.class.getSimpleName();
        volatile boolean stopWork = false;
        Lock mutex = new ReentrantLock();
        Condition waitCondition = mutex.newCondition();
        volatile boolean shouldSendUploadUpdateBroadcast = false;
        volatile boolean shouldSendProgressStatusUpadteBroadcast = false;
        volatile boolean shouldSendTranscodeUpdateBroadcast = false;
        UploadFile currentTranscodingFile = null;
        TranscoderUtils transcoderUtils = new TranscoderUtils();
        TrackEvent trackEvent = new TrackEvent();
        Map<String, MyUpCancellationSingal> myUpCancellationSignalMap = new HashMap<>();

        public ScanThread() {
            transcoderUtils.setCallback(this);
        }

        @Override
        public void run() {
            while (true) {
                mutex.lock();
                if (stopWork) {
                    mutex.unlock();
                    break;
                }
                if (AccountUtil.isLogin()) {
                    handleBroadcast();
                    handleDelete();
                    handleTranscode();
                    handleUpload();
                    handlePublish();
                    if (checkFinish()) {
                        stopSelf();
                    }
                }
                try {
                    waitCondition.await(PublishUtil.SCAN_INTERVAL_MS, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mutex.unlock();
            }
            if (AccountUtil.isLogin()) {
                handleBroadcast();
            }
        }

        public void handleBroadcast() {
            if (shouldSendUploadUpdateBroadcast) {
                sendUploadUpdateBroadcast();
                shouldSendUploadUpdateBroadcast = false;
            }

            if (shouldSendProgressStatusUpadteBroadcast) {
                sendProgressStatusUpdateBroadcast();
                shouldSendProgressStatusUpadteBroadcast = false;
            }

            if (shouldSendTranscodeUpdateBroadcast) {
                sendTranscodeUpdateBroadcast();
                shouldSendTranscodeUpdateBroadcast = false;
            }
        }

        public void handleTranscode() {
            if (currentTranscodingFile == null) {
                List<UploadFile> uploadFileList = new LinkedList<>();
                try {
                    uploadFileList = uploadFileDao.queryBuilder()
                            .where()
                            .eq(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_UPLOAD)
                            .and()
                            .eq(UploadFile.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                            .query();
                } catch (Exception e) {
                    Log.e(TAG, "handleTranscode:" + Log.getStackTraceString(e));
                }
                for (UploadFile uploadFile : uploadFileList) {
                    if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE) {
                        currentTranscodingFile = uploadFile;
                        break;
                    }
                }
                if (currentTranscodingFile != null) {
                    transcoderUtils.start(currentTranscodingFile.getFileLocalUrl());
                }
            }
        }

        public void handleUpload() {
            List<UploadFile> uploadFileList = new LinkedList<>();
            try {
                QueryBuilder<UploadFile, Integer> queryBuilder = uploadFileDao.queryBuilder();
                Where<UploadFile, Integer> where = queryBuilder.where();
                where.and(
                        where.eq(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_UPLOAD)
                                .and()
                                .eq(UploadFile.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                        ,
                        where.eq(UploadFile.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH)
                                .or()
                                .eq(UploadFile.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                .or()
                                .eq(UploadFile.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_UPLOADING)
                );
                uploadFileList = queryBuilder.query();
            } catch (Exception e) {
                Timber.e("handleUpload:" + Log.getStackTraceString(e));
            }
            for (UploadFile uploadFile : uploadFileList) {
                if (uploadFile.getUploadedSize() < uploadFile.getTotalSize()) {
                    if ((System.currentTimeMillis() - uploadFile.getUploadTimestamp()) > PublishUtil.UPLOAD_IDLE_TIMEOUT_MS) {
                        retryUploadFile(uploadFile);
                    }
                }
            }
        }

        public void handlePublish() {
            handleLearnVideoPublish();
            handlePhotoPublish();
            handleNormalVideoPublish();
            handleInfoPublish();
            handleMajorCoursePublish();
            handleTraingClassPublish();
            handleTraingCardPublish();
            handleSpecialTopicPublish();
        }

        public void handleTraingCardPublish() {
            List<TraingCardDBModel> traingCardDBModelList = new LinkedList<>();
            try {
                traingCardDBModelList = TraingCardDBModelDao.getDao().queryBuilder()
                        .where()
                        .eq(TraingCardDBModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_UPLOAD)
                        .and()
                        .eq(TraingCardDBModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                        .query();
            } catch (Exception e) {
                Log.e(TAG, "handleTraingCardPublish:" + Log.getStackTraceString(e));
            }
            for (TraingCardDBModel traingCardDBModel : traingCardDBModelList) {
                switch (traingCardDBModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_REJECT:
                    case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        break;
                    default: {
                        final List<UploadFile> uploadFileList = new LinkedList<>();
                        try {
                            uploadFileList.addAll(uploadFileDao.queryBuilder()
                                    .where()
                                    .eq(UploadFile.PARENT_ID_FIELD, traingCardDBModel.getId())
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                    .query());
                        } catch (Exception e) {
                            Log.e(TAG, "handleTraingCardPublish:" + Log.getStackTraceString(e));
                        }
                        boolean uploadFinish = true;
                        for (UploadFile uploadFile : uploadFileList) {
                            if (uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH && uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_PRE_UPLOAD_FINISH) {
                                uploadFinish = false;
                                break;
                            }
                        }
                        if (uploadFinish) {
                            if (traingCardDBModel.getRetryCount() > PublishUtil.MAX_PUBLISH_RETRY_NUM) {
                                try {
                                    UpdateBuilder<TraingCardDBModel, String> updateBuilder = TraingCardDBModelDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                    updateBuilder.updateColumnValue(TraingCardDBModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                                    updateBuilder.updateColumnValue(TraingCardDBModel.RETRY_COUNT_FIELD, 0);
                                    updateBuilder.where().eq(TraingCardDBModel.ID_FIELD, traingCardDBModel.getId());
                                    updateBuilder.update();
                                    TraingCardDBModelDao.getDao().refresh(traingCardDBModel);
                                    shouldSendProgressStatusUpadteBroadcast = true;
                                } catch (Exception e) {

                                }
                                return;
                            }
                            try {
                                UpdateBuilder<TraingCardDBModel, String> updateBuilder = TraingCardDBModelDao.getDao().updateBuilder();
                                updateBuilder.updateColumnValue(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMITTING);
                                updateBuilder.where().eq(TraingCardDBModel.ID_FIELD, traingCardDBModel.getId());
                                updateBuilder.update();
                                TraingCardDBModelDao.getDao().refresh(traingCardDBModel);
                                shouldSendProgressStatusUpadteBroadcast = true;
                            } catch (Exception e) {
                                Log.e(TAG, "handleTraingCardPublish:" + Log.getStackTraceString(e));
                            }
                            //////////
                            final TraingCardDBModel finalTraingCardDBModel = traingCardDBModel;
                            /////////////////////////////
                            ApiManager.getService().oss().enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.OK) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                        if (ListUtil.isEmpty(ossList)) {
                                            throw new Exception("OSS 列表为空");
                                        }
                                        Oss oss = ossList.get(0);
                                        String photoDomain = oss.getImage().getDomain() + "/";
                                        String videoDomain = oss.getVideo().getDomain() + "/";
                                        Moment moment = new Moment();
                                        if (finalTraingCardDBModel.isCoverNeedUpload()) {
                                            moment.setCover(Arrays.asList(photoDomain + finalTraingCardDBModel.getCoverStoreKey()));
                                        } else {
                                            moment.setCover(Arrays.asList(finalTraingCardDBModel.getCoverUrl()));
                                        }
                                        List<TagBackup> tagList = new LinkedList<>();
                                        List<SelectTagItem> selectTagItemList = JSON.parseArray(finalTraingCardDBModel.getTagJson(), SelectTagItem.class);
                                        for (SelectTagItem selectTagItem : selectTagItemList) {
                                            if (TextUtils.isEmpty(selectTagItem.getId())) continue;
                                            tagList.add(TagBackup.newBuilder()
                                                    .id(selectTagItem.getId())
                                                    .name(selectTagItem.getName())
                                                    .groupType(SetupUtil.GROUP_TYPE_OTHER)
                                                    .build());
                                        }
                                        TrainingCard trainingCard = new TrainingCard();
                                        try {
                                            trainingCard.setPrice(Double.parseDouble(finalTraingCardDBModel.getPrice()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            trainingCard.setDivisionProportion(Double.parseDouble(finalTraingCardDBModel.getPlatformDividend()) / 100);
                                        } catch (Exception e) {

                                        }
                                        switch (finalTraingCardDBModel.getCardType()) {
                                            case TraingCardFormModel.CARD_TYPE_COUNT_CARD:
                                                trainingCard.setCardType(Moment.TRAINING_CARD_TYPE_MEASURED_CARD);
                                                break;
                                            case TraingCardFormModel.CARD_TYPE_PREPAID_CARD:
                                                trainingCard.setCardType(Moment.TRAINING_CARD_TYPE_RECHARGEABLE_CARD);
                                                break;
                                            case TraingCardFormModel.CARD_TYPE_TIME_CARD:
                                                trainingCard.setCardType(Moment.TRAINING_CARD_TYPE_TIME_CARD);
                                                break;
                                        }
                                        switch (finalTraingCardDBModel.getEffectiveType()) {
                                            case TraingCardFormModel.EFFECTIVE_TYPE_ATTENDANCE:
                                                trainingCard.setTakeEffectType(Moment.TRAINING_CARD_TAKE_EFFECT_TYPE_ATTENDANCE);
                                                break;
                                            case TraingCardFormModel.EFFECTIVE_TYPE_IMMEDIATE:
                                                trainingCard.setTakeEffectType(Moment.TRAINING_CARD_TAKE_EFFECT_TYPE_IMMEDIATE);
                                                break;
                                        }
                                        try {
                                            trainingCard.setTakeEffectPeriod(Integer.parseInt(finalTraingCardDBModel.getValidity()));
                                        } catch (Exception e) {

                                        }
                                        trainingCard.setTakeEffectPeriodUnit(Moment.TRAINING_CARD_VALIDITY_UNIT_DAY);
                                        DetailBackup detailBackup = new DetailBackup();
                                        CourseDescriptionModel courseDescriptionModel = JSON.parseObject(finalTraingCardDBModel.getCourseDesc(), CourseDescriptionModel.class);
                                        List<Content> coverList = PublishUtil.convertCourseCoverToContent(photoDomain, videoDomain, courseDescriptionModel.getCourseCoverList());
                                        trainingCard.setCoverSet(coverList);
                                        List<Course> courseList = JSON.parseArray(finalTraingCardDBModel.getCourse(), Course.class);
                                        trainingCard.setBindCourseBackup(new LinkedList<CourseBackup>());
                                        for (Course course : courseList) {
                                            CourseBackup courseBackup = new CourseBackup();
                                            courseBackup.setId(course.getId());
                                            courseBackup.setTitle(course.getTitle());
                                            try {
                                                courseBackup.setBindUnitPrice(Double.parseDouble(course.getSinglePrice()));
                                            } catch (Exception e) {
                                                courseBackup.setBindUnitPrice(null);
                                            }
                                            switch (course.getType()) {
                                                case Course.TYPE_MAJOR_COURSE:
                                                    courseBackup.setSubject(Moment.SUBJECT_MAJOR_COURSE);
                                                    break;
                                                case Course.TYPE_TRAING_CLASS:
                                                    courseBackup.setSubject(Moment.SUBJECT_TRAINING_COURSE);
                                                    break;
                                            }
                                            trainingCard.getBindCourseBackup().add(courseBackup);
                                        }

                                        List<Content> courseDescContentList = PublishUtil.convertArticleToContent(photoDomain, videoDomain, courseDescriptionModel.getArticleNodeList());
                                        detailBackup.setContent(courseDescContentList);
                                        detailBackup.setGuarantee(new LinkedList<Guarantee>());
                                        List<GuaranteeItem> guaranteeItemList = JSON.parseArray(finalTraingCardDBModel.getGuarantee(), GuaranteeItem.class);
                                        for (GuaranteeItem guaranteeItem : guaranteeItemList) {
                                            if (TextUtils.isEmpty(guaranteeItem.getId())) continue;
                                            Guarantee guarantee = new Guarantee();
                                            guarantee.setId(guaranteeItem.getId());
                                            guarantee.setDetail(guaranteeItem.getContent());
                                            guarantee.setName(guaranteeItem.getTitle());
                                            detailBackup.getGuarantee().add(guarantee);
                                        }
                                        moment.setLetBuy(null);
                                        moment.setTags(tagList);
                                        moment.setCreator(finalTraingCardDBModel.getUserId());
                                        moment.setTitle(finalTraingCardDBModel.getTitle());
                                        moment.setMoreBackup(JSON.toJSONString(trainingCard));
                                        moment.setCreateTime(finalTraingCardDBModel.getReleaseDate());
                                        moment.setSubject(Moment.SUBJECT_TRAINING_CARD);
                                        moment.setDetailBackup(detailBackup);
                                        ///
                                        Call<ResponseBody> momentCall;
                                        switch (finalTraingCardDBModel.getPublishOperationType()) {
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE:
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_SAVE:
                                                momentCall = ApiManager.getService().momentSaveOnly(moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW:
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW:
                                                momentCall = ApiManager.getService().momentPublish(moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE:
                                                momentCall = ApiManager.getService().editMoment(finalTraingCardDBModel.getGoodsId(), ActionEngine.SAVE, moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW:
                                                momentCall = ApiManager.getService().editMoment(finalTraingCardDBModel.getGoodsId(), ActionEngine.PUBLISH, moment);
                                                break;
                                            default:
                                                momentCall = ApiManager.getService().momentPublish(moment);
                                                break;

                                        }
                                        momentCall.enqueue(new Callback<ResponseBody>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                try {
                                                    if (response.code() != ResponseCode.CREATED) {
                                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                    }
                                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                                    Moment respMoment = JSON.parseObject(json, Moment.class);
                                                    int progressStatus;
                                                    switch (respMoment.getStatus()) {
                                                        case Moment.STATUS_IN_REVIEW:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                                                            break;
                                                        case Moment.STATUS_REJECT:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                                                            break;
                                                        case Moment.STATUS_PUT_ON:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_SAVE:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_REVIEW_PASSED:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_GET_OFF:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_TRANSCODING:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                                                            break;
                                                        default:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                    }
                                                    UpdateBuilder<TraingCardDBModel, String> updateBuilder = TraingCardDBModelDao.getDao().updateBuilder();
                                                    updateBuilder.updateColumnValue(TraingCardDBModel.GOODS_ID_FIELD, respMoment.getId());
                                                    updateBuilder.updateColumnValue(TraingCardDBModel.PROGRESS_STATUS_FIELD, progressStatus);
                                                    updateBuilder.updateColumnValue(TraingCardDBModel.ROUTER_FIELD, respMoment.getRouter());
                                                    updateBuilder.where().eq(TraingCardDBModel.ID_FIELD, finalTraingCardDBModel.getId());
                                                    updateBuilder.update();
                                                    TraingCardDBModelDao.getDao().refresh(finalTraingCardDBModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    onFailure(call, e);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                Timber.e("onFailure:" + Log.getStackTraceString(t));
                                                try {
                                                    UpdateBuilder<TraingCardDBModel, String> updateBuilder = TraingCardDBModelDao.getDao().updateBuilder();
                                                    updateBuilder.updateColumnValue(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                                    updateBuilder.updateColumnValue(TraingCardDBModel.RETRY_COUNT_FIELD, finalTraingCardDBModel.getRetryCount() + 1);
                                                    updateBuilder.where().eq(TraingCardDBModel.ID_FIELD, finalTraingCardDBModel.getId());
                                                    updateBuilder.update();
                                                    TraingCardDBModelDao.getDao().refresh(finalTraingCardDBModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                                }
                                            }
                                        });
                                        ///////////////
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Timber.e("onFailure:" + Log.getStackTraceString(t));
                                    try {
                                        UpdateBuilder<TraingCardDBModel, String> updateBuilder = TraingCardDBModelDao.getDao().updateBuilder();
                                        updateBuilder.updateColumnValue(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                        updateBuilder.updateColumnValue(TraingCardDBModel.RETRY_COUNT_FIELD, finalTraingCardDBModel.getRetryCount() + 1);
                                        updateBuilder.where().eq(TraingCardDBModel.ID_FIELD, finalTraingCardDBModel.getId());
                                        updateBuilder.update();
                                        TraingCardDBModelDao.getDao().refresh(finalTraingCardDBModel);
                                        shouldSendProgressStatusUpadteBroadcast = true;
                                    } catch (Exception e) {
                                        Log.e(TAG, "handleTraingCardPublish:" + Log.getStackTraceString(e));
                                    }
                                }
                            });
                            ////////////////////////////

                        }
                        break;
                    }

                }
            }
        }

        public void handleTraingClassPublish() {
            List<TraingClassDBModel> traingClassDBModelList = new LinkedList<>();
            try {
                traingClassDBModelList = TraingClassDBModelDao.getDao().queryBuilder()
                        .where()
                        .eq(TraingClassDBModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_UPLOAD)
                        .and()
                        .eq(TraingClassDBModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                        .query();
            } catch (Exception e) {
                Log.e(TAG, "handleTraingClassPublish:" + Log.getStackTraceString(e));
            }
            for (TraingClassDBModel traingClassDBModel : traingClassDBModelList) {
                switch (traingClassDBModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_REJECT:
                    case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        break;
                    default: {
                        final List<UploadFile> uploadFileList = new LinkedList<>();
                        try {
                            uploadFileList.addAll(uploadFileDao.queryBuilder()
                                    .where()
                                    .eq(UploadFile.PARENT_ID_FIELD, traingClassDBModel.getId())
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                    .query());
                        } catch (Exception e) {
                            Log.e(TAG, "handleTraingClassPublish:" + Log.getStackTraceString(e));
                        }
                        boolean uploadFinish = true;
                        for (UploadFile uploadFile : uploadFileList) {
                            if (uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH && uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_PRE_UPLOAD_FINISH) {
                                uploadFinish = false;
                                break;
                            }
                        }
                        if (uploadFinish) {
                            if (traingClassDBModel.getRetryCount() > PublishUtil.MAX_PUBLISH_RETRY_NUM) {
                                try {
                                    UpdateBuilder<TraingClassDBModel, String> updateBuilder = TraingClassDBModelDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                    updateBuilder.updateColumnValue(TraingClassDBModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                                    updateBuilder.updateColumnValue(TraingClassDBModel.RETRY_COUNT_FIELD, 0);
                                    updateBuilder.where().eq(TraingClassDBModel.ID_FIELD, traingClassDBModel.getId());
                                    updateBuilder.update();
                                    TraingClassDBModelDao.getDao().refresh(traingClassDBModel);
                                    shouldSendProgressStatusUpadteBroadcast = true;
                                } catch (Exception e) {

                                }
                                return;
                            }
                            try {
                                UpdateBuilder<TraingClassDBModel, String> updateBuilder = TraingClassDBModelDao.getDao().updateBuilder();
                                updateBuilder.updateColumnValue(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMITTING);
                                updateBuilder.where().eq(TraingClassDBModel.ID_FIELD, traingClassDBModel.getId());
                                updateBuilder.update();
                                TraingClassDBModelDao.getDao().refresh(traingClassDBModel);
                                shouldSendProgressStatusUpadteBroadcast = true;
                            } catch (Exception e) {
                                Log.e(TAG, "handleTraingClassPublish:" + Log.getStackTraceString(e));
                            }
                            //////////
                            final TraingClassDBModel finalTraingClassDBModel = traingClassDBModel;
                            /////////////////////////////
                            ApiManager.getService().oss().enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.OK) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                        if (ListUtil.isEmpty(ossList)) {
                                            throw new Exception("OSS 列表为空");
                                        }
                                        Oss oss = ossList.get(0);
                                        String photoDomain = oss.getImage().getDomain() + "/";
                                        String videoDomain = oss.getVideo().getDomain() + "/";
                                        Moment moment = new Moment();
                                        if (finalTraingClassDBModel.isCoverNeedUpload()) {
                                            moment.setCover(Arrays.asList(photoDomain + finalTraingClassDBModel.getCoverStoreKey()));
                                        } else {
                                            moment.setCover(Arrays.asList(finalTraingClassDBModel.getCoverUrl()));
                                        }


                                        List<TagBackup> tagList = new LinkedList<>();
                                        List<SelectTagItem> selectTagItemList = JSON.parseArray(finalTraingClassDBModel.getTagJson(), SelectTagItem.class);
                                        for (SelectTagItem selectTagItem : selectTagItemList) {
                                            if (TextUtils.isEmpty(selectTagItem.getId())) continue;
                                            tagList.add(TagBackup.newBuilder()
                                                    .id(selectTagItem.getId())
                                                    .name(selectTagItem.getName())
                                                    .groupType(SetupUtil.GROUP_TYPE_OTHER)
                                                    .build());
                                        }

                                        List<SuitableLearnAgeItem> suitableLearnAgeItemList = JSON.parseArray(finalTraingClassDBModel.getSuitableLearnAge(), SuitableLearnAgeItem.class);
                                        for (SuitableLearnAgeItem suitableLearnAgeItem : suitableLearnAgeItemList) {
                                            if (TextUtils.isEmpty(suitableLearnAgeItem.getId()))
                                                continue;
                                            tagList.add(TagBackup.newBuilder()
                                                    .id(suitableLearnAgeItem.getId())
                                                    .name(suitableLearnAgeItem.getTitle())
                                                    .groupType(SetupUtil.GROUP_TYPE_LEARN_AGE)
                                                    .build());
                                        }
                                        List<SelectLearnTargetItem> selectLearnTargetItemList = JSON.parseArray(finalTraingClassDBModel.getLearnTarget(), SelectLearnTargetItem.class);
                                        for (SelectLearnTargetItem selectLearnTargetItem : selectLearnTargetItemList) {
                                            if (TextUtils.isEmpty(selectLearnTargetItem.getId()))
                                                continue;
                                            tagList.add(TagBackup.newBuilder()
                                                    .id(selectLearnTargetItem.getId())
                                                    .name(selectLearnTargetItem.getTitle())
                                                    .groupType(SetupUtil.GROUP_TYPE_LEARN_TARGET)
                                                    .build());
                                        }
                                        SelectSuitablePeopleItem selectSuitablePeopleItem = JSON.parseObject(finalTraingClassDBModel.getSuitablePeople(), SelectSuitablePeopleItem.class);
                                        if (!TextUtils.isEmpty(selectSuitablePeopleItem.getId())) {
                                            tagList.add(TagBackup.newBuilder()
                                                    .id(selectSuitablePeopleItem.getId())
                                                    .name(selectSuitablePeopleItem.getTitle())
                                                    .groupType(SetupUtil.GROUP_TYPE_SUITABLE_PEOPLE)
                                                    .build());
                                        }

                                        PublishInterestItem publishInterestItem = JSON.parseObject(finalTraingClassDBModel.getInterest(), PublishInterestItem.class);
                                        tagList.add(TagBackup.newBuilder()
                                                .id(publishInterestItem.getId())
                                                .name(publishInterestItem.getTitle())
                                                .groupType(SetupUtil.GROUP_TYPE_CATEGORY)
                                                .subGroupType(publishInterestItem.getParent().getId())
                                                .subGroupName(publishInterestItem.getParent().getTitle())
                                                .build());


                                        ClassLocation classLocation = JSON.parseObject(finalTraingClassDBModel.getClassLocation(), ClassLocation.class);
                                        TrainingCourse traingCourse = new TrainingCourse();
                                        try {
                                            traingCourse.setClassroomSumary(classLocation.getProvince() + " " + classLocation.getCity());
                                        } catch (Exception e) {

                                        }

                                        try {
                                            traingCourse.setPrice(Double.parseDouble(finalTraingClassDBModel.getPrice()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            traingCourse.setOriginPrice(Double.parseDouble(finalTraingClassDBModel.getPrice()));
                                        } catch (Exception e) {
                                        }
                                        try {
                                            traingCourse.setUnitPrice(Double.parseDouble(finalTraingClassDBModel.getSinglePrice()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            traingCourse.setDivisionProportion(Double.parseDouble(finalTraingClassDBModel.getPlatformDividend()) / 100);
                                        } catch (Exception e) {

                                        }

                                        traingCourse.setStartDate(finalTraingClassDBModel.getStartClassDate());
                                        traingCourse.setEndDate(finalTraingClassDBModel.getEndClassDate());
                                        try {
                                            traingCourse.setClassCount(Integer.parseInt(finalTraingClassDBModel.getCourseNumber()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            traingCourse.setDruationPerClass(Integer.parseInt(finalTraingClassDBModel.getSingleClassDuration()));
                                        } catch (Exception e) {

                                        }
                                        switch (finalTraingClassDBModel.getOpenClassCondition()) {
                                            case TraingClassFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_OPEN_DATE:
                                                traingCourse.setTakeEffectCondition(Moment.COURSE_TAKE_EFFECT_CONDITION_OPEN_DATE);
                                                break;
                                            case TraingClassFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_POPULATION:
                                                traingCourse.setTakeEffectCondition(Moment.COURSE_TAKE_EFFECT_CONDITION_POPULATION);
                                                break;
                                        }

                                        traingCourse.setConfirmStartClassDate(finalTraingClassDBModel.getConfirmDate());
                                        try {
                                            traingCourse.setStudentMax(Integer.parseInt(finalTraingClassDBModel.getClassSize()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            traingCourse.setStudentMin(Integer.parseInt(finalTraingClassDBModel.getMinClassSize()));
                                        } catch (Exception e) {

                                        }

                                        CourseScheduleModel courseScheduleModel = JSON.parseObject(finalTraingClassDBModel.getCourseSchedule(), CourseScheduleModel.class);
                                        List<Content> courseScheduleContentList = PublishUtil.convertArticleToContent(photoDomain, videoDomain, courseScheduleModel.getArticleNodeList());
                                        DetailBackup detailBackup = new DetailBackup();
                                        traingCourse.setTimetable(courseScheduleContentList);
                                        CourseDescriptionModel courseDescriptionModel = JSON.parseObject(finalTraingClassDBModel.getCourseDesc(), CourseDescriptionModel.class);
                                        List<Content> coverList = PublishUtil.convertCourseCoverToContent(photoDomain, videoDomain, courseDescriptionModel.getCourseCoverList());
                                        traingCourse.setCoverSet(coverList);
                                        List<TraingCard> traingCardList = JSON.parseArray(finalTraingClassDBModel.getTraingCard(), TraingCard.class);
                                        traingCourse.setBindCardBackup(new LinkedList<CardBackup>());
                                        for (TraingCard traingCard : traingCardList) {
                                            CardBackup cardBackup = new CardBackup();
                                            cardBackup.setId(traingCard.getId());
                                            cardBackup.setTitle(traingCard.getTitle());
                                            switch (traingCard.getType()) {
                                                case TraingCard.TYPE_COUNT_CARD:
                                                    cardBackup.setCardType(Moment.TRAINING_CARD_TYPE_MEASURED_CARD);
                                                    break;
                                                case TraingCard.TYPE_PREPAID_CARD:
                                                    cardBackup.setCardType(Moment.TRAINING_CARD_TYPE_RECHARGEABLE_CARD);
                                                    break;
                                                case TraingCard.TYPE_TIME_CARD:
                                                    cardBackup.setCardType(Moment.TRAINING_CARD_TYPE_TIME_CARD);
                                                    break;
                                            }
                                            traingCourse.getBindCardBackup().add(cardBackup);
                                        }
                                        List<Content> courseDescContentList = PublishUtil.convertArticleToContent(photoDomain, videoDomain, courseDescriptionModel.getArticleNodeList());
                                        detailBackup.setContent(courseDescContentList);
                                        detailBackup.setGuarantee(new LinkedList<Guarantee>());
                                        List<GuaranteeItem> guaranteeItemList = JSON.parseArray(finalTraingClassDBModel.getGuarantee(), GuaranteeItem.class);
                                        for (GuaranteeItem guaranteeItem : guaranteeItemList) {
                                            if (TextUtils.isEmpty(guaranteeItem.getId())) continue;
                                            Guarantee guarantee = new Guarantee();
                                            guarantee.setId(guaranteeItem.getId());
                                            guarantee.setDetail(guaranteeItem.getContent());
                                            guarantee.setName(guaranteeItem.getTitle());
                                            detailBackup.getGuarantee().add(guarantee);
                                        }
                                        moment.setLetBuy(finalTraingClassDBModel.isOpenBuy());
                                        moment.setTags(tagList);
                                        moment.setCreator(finalTraingClassDBModel.getUserId());
                                        moment.setCityId(classLocation.getId());
                                        moment.setTitle(finalTraingClassDBModel.getTitle());
                                        moment.setMoreBackup(JSON.toJSONString(traingCourse));
                                        moment.setCreateTime(finalTraingClassDBModel.getReleaseDate());
                                        moment.setSubject(Moment.SUBJECT_TRAINING_COURSE);
                                        moment.setDetailBackup(detailBackup);
                                        moment.setCategoryId(publishInterestItem.getId());
                                        moment.setChannel(publishInterestItem.getParent().getId());
                                        ///
                                        Call<ResponseBody> momentCall;
                                        switch (finalTraingClassDBModel.getPublishOperationType()) {
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE:
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_SAVE:
                                                momentCall = ApiManager.getService().momentSaveOnly(moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW:
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW:
                                                momentCall = ApiManager.getService().momentPublish(moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE:
                                                momentCall = ApiManager.getService().editMoment(finalTraingClassDBModel.getGoodsId(), ActionEngine.SAVE, moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW:
                                                momentCall = ApiManager.getService().editMoment(finalTraingClassDBModel.getGoodsId(), ActionEngine.PUBLISH, moment);
                                                break;
                                            default:
                                                momentCall = ApiManager.getService().momentPublish(moment);
                                                break;

                                        }
                                        momentCall.enqueue(new Callback<ResponseBody>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                try {
                                                    if (response.code() != ResponseCode.CREATED) {
                                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                    }
                                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                                    Moment respMoment = JSON.parseObject(json, Moment.class);
                                                    UpdateBuilder<TraingClassDBModel, String> updateBuilder = TraingClassDBModelDao.getDao().updateBuilder();
                                                    updateBuilder.updateColumnValue(TraingClassDBModel.GOODS_ID_FIELD, respMoment.getId());
                                                    int progressStatus;
                                                    switch (respMoment.getStatus()) {
                                                        case Moment.STATUS_IN_REVIEW:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                                                            break;
                                                        case Moment.STATUS_REJECT:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                                                            break;
                                                        case Moment.STATUS_PUT_ON:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_SAVE:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_REVIEW_PASSED:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_GET_OFF:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_TRANSCODING:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                                                            break;
                                                        default:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                    }
                                                    updateBuilder.updateColumnValue(TraingClassDBModel.PROGRESS_STATUS_FIELD, progressStatus);
                                                    updateBuilder.updateColumnValue(TraingClassDBModel.ROUTER_FIELD, respMoment.getRouter());
                                                    updateBuilder.where().eq(TraingClassDBModel.ID_FIELD, finalTraingClassDBModel.getId());
                                                    updateBuilder.update();
                                                    TraingClassDBModelDao.getDao().refresh(finalTraingClassDBModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    onFailure(call, e);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                Timber.e("onFailure:" + Log.getStackTraceString(t));
                                                try {
                                                    UpdateBuilder<TraingClassDBModel, String> updateBuilder = TraingClassDBModelDao.getDao().updateBuilder();
                                                    updateBuilder.updateColumnValue(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                                    updateBuilder.updateColumnValue(TraingClassDBModel.RETRY_COUNT_FIELD, finalTraingClassDBModel.getRetryCount() + 1);
                                                    updateBuilder.where().eq(TraingClassDBModel.ID_FIELD, finalTraingClassDBModel.getId());
                                                    updateBuilder.update();
                                                    TraingClassDBModelDao.getDao().refresh(finalTraingClassDBModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                                }
                                            }
                                        });
                                        ///////////////
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Timber.e("onFailure:" + Log.getStackTraceString(t));
                                    try {
                                        UpdateBuilder<TraingClassDBModel, String> updateBuilder = TraingClassDBModelDao.getDao().updateBuilder();
                                        updateBuilder.updateColumnValue(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                        updateBuilder.updateColumnValue(TraingClassDBModel.RETRY_COUNT_FIELD, finalTraingClassDBModel.getRetryCount() + 1);
                                        updateBuilder.where().eq(TraingClassDBModel.ID_FIELD, finalTraingClassDBModel.getId());
                                        updateBuilder.update();
                                        TraingClassDBModelDao.getDao().refresh(finalTraingClassDBModel);
                                        shouldSendProgressStatusUpadteBroadcast = true;
                                    } catch (Exception e) {
                                        Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                    }
                                }
                            });
                            ////////////////////////////

                        }
                        break;
                    }

                }
            }
        }

        public void handleMajorCoursePublish() {
            List<MajorCourseDBModel> majorCourseDBModelList = new LinkedList<>();
            try {
                majorCourseDBModelList = MajorCourseDBModelDao.getDao().queryBuilder()
                        .where()
                        .eq(MajorCourseDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_UPLOAD)
                        .and()
                        .eq(MajorCourseDBModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .query();
            } catch (Exception e) {
                Log.e(TAG, "handleMajorCoursePublish:" + Log.getStackTraceString(e));
            }
            for (final MajorCourseDBModel majorCourseDBModel : majorCourseDBModelList) {
                switch (majorCourseDBModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_REJECT:
                    case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        break;
                    default: {
                        final List<UploadFile> uploadFileList = new LinkedList<>();
                        try {
                            uploadFileList.addAll(uploadFileDao.queryBuilder()
                                    .where()
                                    .eq(UploadFile.PARENT_ID_FIELD, majorCourseDBModel.getId())
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                    .query());
                        } catch (Exception e) {
                            Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                        }
                        boolean uploadFinish = true;
                        for (UploadFile uploadFile : uploadFileList) {
                            if (uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH && uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_PRE_UPLOAD_FINISH) {
                                uploadFinish = false;
                                break;
                            }
                        }
                        if (uploadFinish) {
                            if (majorCourseDBModel.getRetryCount() > PublishUtil.MAX_PUBLISH_RETRY_NUM) {
                                try {
                                    UpdateBuilder<MajorCourseDBModel, String> updateBuilder = MajorCourseDBModelDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                    updateBuilder.updateColumnValue(MajorCourseDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                                    updateBuilder.updateColumnValue(MajorCourseDBModel.RETRY_COUNT, 0);
                                    updateBuilder.where().eq(MajorCourseDBModel.ID, majorCourseDBModel.getId());
                                    updateBuilder.update();
                                    MajorCourseDBModelDao.getDao().refresh(majorCourseDBModel);
                                    shouldSendProgressStatusUpadteBroadcast = true;
                                } catch (Exception e) {

                                }
                                return;
                            }
                            try {
                                UpdateBuilder<MajorCourseDBModel, String> updateBuilder = MajorCourseDBModelDao.getDao().updateBuilder();
                                updateBuilder.updateColumnValue(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMITTING);
                                updateBuilder.where().eq(MajorCourseDBModel.ID, majorCourseDBModel.getId());
                                updateBuilder.update();
                                MajorCourseDBModelDao.getDao().refresh(majorCourseDBModel);
                                shouldSendProgressStatusUpadteBroadcast = true;
                            } catch (Exception e) {
                                Log.e(TAG, "handleMajorCoursePublish:" + Log.getStackTraceString(e));
                            }
                            //////////
                            final MajorCourseDBModel finalMajorCourseDBModel = majorCourseDBModel;
                            /////////////////////////////
                            ApiManager.getService().oss().enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.OK) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                        if (ListUtil.isEmpty(ossList)) {
                                            throw new Exception("OSS 列表为空");
                                        }
                                        Oss oss = ossList.get(0);
                                        String photoDomain = oss.getImage().getDomain() + "/";
                                        String videoDomain = oss.getVideo().getDomain() + "/";
                                        Moment moment = new Moment();
                                        if (finalMajorCourseDBModel.isCoverNeedUpload()) {
                                            moment.setCover(Arrays.asList(photoDomain + finalMajorCourseDBModel.getCoverStoreKey()));
                                        } else {
                                            moment.setCover(Arrays.asList(finalMajorCourseDBModel.getCoverUrl()));
                                        }


                                        List<TagBackup> tagList = new LinkedList<>();
                                        List<Interest> industryList = JSON.parseArray(finalMajorCourseDBModel.getIndustry(), Interest.class);
                                        tagList.addAll(InterestUtil.convertInterestListToTagBackupList(industryList));
                                        List<Interest> interestList = JSON.parseArray(finalMajorCourseDBModel.getInterest(), Interest.class);
                                        tagList.addAll(InterestUtil.convertInterestListToTagBackupList(interestList));
                                        MajorCourseType majorCourseType = JSON.parseObject(finalMajorCourseDBModel.getMajorCourseType(), MajorCourseType.class);
                                        tagList.add(TagBackup.newBuilder()
                                                .id(majorCourseType.getId())
                                                .name(majorCourseType.getTitle())
                                                .groupType(SetupUtil.GROUP_TYPE_MAJOR_COURSE_TYPE)
                                                .build());

                                        ClassLocation classLocation = JSON.parseObject(finalMajorCourseDBModel.getClassLocation(), ClassLocation.class);
                                        MajorCourse majorCourse = new MajorCourse();
                                        try {
                                            majorCourse.setClassroomSumary(classLocation.getProvince() + " " + classLocation.getCity());
                                        } catch (Exception e) {

                                        }
                                        try {
                                            majorCourse.setPrice(Double.parseDouble(finalMajorCourseDBModel.getPrice()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            majorCourse.setOriginPrice(Double.parseDouble(finalMajorCourseDBModel.getPrice()));
                                        } catch (Exception e) {
                                        }
                                        try {
                                            majorCourse.setUnitPrice(Double.parseDouble(finalMajorCourseDBModel.getSinglePrice()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            majorCourse.setDivisionProportion(Double.parseDouble(finalMajorCourseDBModel.getPlatformDividend()) / 100);
                                        } catch (Exception e) {

                                        }
                                        majorCourse.setSuitablePopulation(finalMajorCourseDBModel.getSuitablePeople());
                                        majorCourse.setLearningAges(finalMajorCourseDBModel.getSuitableLearnAge());
                                        majorCourse.setLearningGoals(finalMajorCourseDBModel.getLearnTarget());
                                        majorCourse.setStartDate(finalMajorCourseDBModel.getStartClassDate());
                                        majorCourse.setEndDate(finalMajorCourseDBModel.getEndClassDate());
                                        majorCourse.setConsumptionGuarantee(finalMajorCourseDBModel.isJoinConsumptionSecurityPlan());
                                        try {
                                            majorCourse.setClassCount(Integer.parseInt(finalMajorCourseDBModel.getCourseNumber()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            majorCourse.setDruationPerClass(Integer.parseInt(finalMajorCourseDBModel.getSingleClassDuration()));
                                        } catch (Exception e) {

                                        }
                                        switch (finalMajorCourseDBModel.getOpenClassCondition()) {
                                            case MajorCourseFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_OPEN_DATE:
                                                majorCourse.setTakeEffectCondition(Moment.COURSE_TAKE_EFFECT_CONDITION_OPEN_DATE);
                                                break;
                                            case MajorCourseFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_POPULATION:
                                                majorCourse.setTakeEffectCondition(Moment.COURSE_TAKE_EFFECT_CONDITION_POPULATION);
                                                break;
                                        }

                                        majorCourse.setConfirmStartClassDate(finalMajorCourseDBModel.getConfirmDate());
                                        try {
                                            majorCourse.setStudentMax(Integer.parseInt(finalMajorCourseDBModel.getClassSize()));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            majorCourse.setStudentMin(Integer.parseInt(finalMajorCourseDBModel.getMinClassSize()));
                                        } catch (Exception e) {

                                        }

                                        CourseScheduleModel courseScheduleModel = JSON.parseObject(finalMajorCourseDBModel.getCourseSchedule(), CourseScheduleModel.class);
                                        List<Content> courseScheduleContentList = PublishUtil.convertArticleToContent(photoDomain, videoDomain, courseScheduleModel.getArticleNodeList());
                                        DetailBackup detailBackup = new DetailBackup();
                                        majorCourse.setTimetable(courseScheduleContentList);
                                        CourseDescriptionModel courseDescriptionModel = JSON.parseObject(finalMajorCourseDBModel.getCourseDesc(), CourseDescriptionModel.class);
                                        List<Content> coverList = PublishUtil.convertCourseCoverToContent(photoDomain, videoDomain, courseDescriptionModel.getCourseCoverList());
                                        majorCourse.setCoverSet(coverList);
                                        List<TraingCard> traingCardList = JSON.parseArray(finalMajorCourseDBModel.getTraingCard(), TraingCard.class);
                                        majorCourse.setBindCardBackup(new LinkedList<CardBackup>());
                                        for (TraingCard traingCard : traingCardList) {
                                            CardBackup cardBackup = new CardBackup();
                                            cardBackup.setId(traingCard.getId());
                                            cardBackup.setTitle(traingCard.getTitle());
                                            switch (traingCard.getType()) {
                                                case TraingCard.TYPE_COUNT_CARD:
                                                    cardBackup.setCardType(Moment.TRAINING_CARD_TYPE_MEASURED_CARD);
                                                    break;
                                                case TraingCard.TYPE_PREPAID_CARD:
                                                    cardBackup.setCardType(Moment.TRAINING_CARD_TYPE_RECHARGEABLE_CARD);
                                                    break;
                                                case TraingCard.TYPE_TIME_CARD:
                                                    cardBackup.setCardType(Moment.TRAINING_CARD_TYPE_TIME_CARD);
                                                    break;
                                            }
                                            majorCourse.getBindCardBackup().add(cardBackup);
                                        }
                                        List<Content> coruseDescContentList = PublishUtil.convertArticleToContent(photoDomain, videoDomain, courseDescriptionModel.getArticleNodeList());
                                        detailBackup.setContent(coruseDescContentList);
                                        detailBackup.setGuarantee(new LinkedList<Guarantee>());
                                        List<GuaranteeItem> guaranteeItemList = JSON.parseArray(finalMajorCourseDBModel.getGuarantee(), GuaranteeItem.class);
                                        for (GuaranteeItem guaranteeItem : guaranteeItemList) {
                                            if (TextUtils.isEmpty(guaranteeItem.getId())) continue;
                                            Guarantee guarantee = new Guarantee();
                                            guarantee.setId(guaranteeItem.getId());
                                            guarantee.setDetail(guaranteeItem.getContent());
                                            guarantee.setName(guaranteeItem.getTitle());
                                            detailBackup.getGuarantee().add(guarantee);
                                        }
                                        List<Persistent> persistentList = new LinkedList<>();
                                        majorCourse.setRichText(RichTextUtil.handleRichText(photoDomain, videoDomain, courseDescriptionModel.getRteModel(), persistentList));
                                        majorCourse.setTimetableRichText(RichTextUtil.handleRichText(photoDomain, videoDomain, courseScheduleModel.getRteModel(), persistentList));
                                        majorCourse.setPersistentMappings(RichTextUtil.convertToPersistentMappingList(persistentList));
                                        moment.setLetBuy(finalMajorCourseDBModel.isOpenBuy());
                                        moment.setTags(tagList);
                                        moment.setCreator(finalMajorCourseDBModel.getUserId());
                                        moment.setCityId(classLocation.getId());
                                        moment.setTitle(finalMajorCourseDBModel.getTitle());
                                        moment.setMoreBackup(JSON.toJSONString(majorCourse));
                                        moment.setCreateTime(finalMajorCourseDBModel.getReleaseDate());
                                        moment.setSubject(Moment.SUBJECT_MAJOR_COURSE);
                                        moment.setDetailBackup(detailBackup);
                                        moment.setChannel(ListUtil.getFirstItem(industryList) == null ? "" : ListUtil.getFirstItem(industryList).getId());
                                        ///
                                        Call<ResponseBody> momentCall;
                                        switch (finalMajorCourseDBModel.getPublishOperationType()) {
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE:
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_SAVE:
                                                momentCall = ApiManager.getService().momentSaveOnly(moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW:
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW:
                                                momentCall = ApiManager.getService().momentPublish(moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE:
                                                momentCall = ApiManager.getService().editMoment(finalMajorCourseDBModel.getGoodsId(), ActionEngine.SAVE, moment);
                                                break;
                                            case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW:
                                                momentCall = ApiManager.getService().editMoment(finalMajorCourseDBModel.getGoodsId(), ActionEngine.PUBLISH, moment);
                                                break;
                                            default:
                                                momentCall = ApiManager.getService().momentPublish(moment);
                                                break;

                                        }
                                        momentCall.enqueue(new Callback<ResponseBody>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                try {
                                                    if (response.code() != ResponseCode.CREATED) {
                                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                    }
                                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                                    Moment respMoment = JSON.parseObject(json, Moment.class);
                                                    int progressStatus;
                                                    switch (respMoment.getStatus()) {
                                                        case Moment.STATUS_IN_REVIEW:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                                                            break;
                                                        case Moment.STATUS_REJECT:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                                                            break;
                                                        case Moment.STATUS_PUT_ON:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_SAVE:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_REVIEW_PASSED:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_GET_OFF:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_TRANSCODING:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                                                            break;
                                                        default:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                    }
                                                    UpdateBuilder<MajorCourseDBModel, String> updateBuilder = MajorCourseDBModelDao.getDao().updateBuilder();
                                                    updateBuilder.updateColumnValue(MajorCourseDBModel.GOODS_ID, respMoment.getId());
                                                    updateBuilder.updateColumnValue(MajorCourseDBModel.PROGRESS_STATUS, progressStatus);
                                                    updateBuilder.updateColumnValue(MajorCourseDBModel.ROUTER, respMoment.getRouter());
                                                    updateBuilder.where().eq(MajorCourseDBModel.ID, finalMajorCourseDBModel.getId());
                                                    updateBuilder.update();
                                                    MajorCourseDBModelDao.getDao().refresh(finalMajorCourseDBModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    onFailure(call, e);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                Timber.e("onFailure:" + Log.getStackTraceString(t));
                                                try {
                                                    UpdateBuilder<MajorCourseDBModel, String> updateBuilder = MajorCourseDBModelDao.getDao().updateBuilder();
                                                    updateBuilder.updateColumnValue(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                                    updateBuilder.updateColumnValue(MajorCourseDBModel.RETRY_COUNT, finalMajorCourseDBModel.getRetryCount() + 1);
                                                    updateBuilder.where().eq(MajorCourseDBModel.ID, finalMajorCourseDBModel.getId());
                                                    updateBuilder.update();
                                                    MajorCourseDBModelDao.getDao().refresh(finalMajorCourseDBModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                                }
                                            }
                                        });
                                        ///////////////
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Timber.e("onFailure:" + Log.getStackTraceString(t));
                                    try {
                                        UpdateBuilder<MajorCourseDBModel, String> updateBuilder = MajorCourseDBModelDao.getDao().updateBuilder();
                                        updateBuilder.updateColumnValue(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                        updateBuilder.updateColumnValue(MajorCourseDBModel.RETRY_COUNT, finalMajorCourseDBModel.getRetryCount() + 1);
                                        updateBuilder.where().eq(MajorCourseDBModel.ID, finalMajorCourseDBModel.getId());
                                        updateBuilder.update();
                                        MajorCourseDBModelDao.getDao().refresh(finalMajorCourseDBModel);
                                        shouldSendProgressStatusUpadteBroadcast = true;
                                    } catch (Exception e) {
                                        Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                    }
                                }
                            });
                            ////////////////////////////

                        }
                        break;
                    }

                }
            }
        }

        public void handlePhotoPublish() {
            List<PhotoModel> photoModelList = new LinkedList<>();
            try {
                photoModelList = photoModelDao.queryBuilder()
                        .where()
                        .eq(PhotoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_UPLOAD)
                        .and()
                        .eq(PhotoModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .query();
            } catch (Exception e) {
                Log.e(TAG, "handlePhotoPublish:" + Log.getStackTraceString(e));
            }
            for (PhotoModel photoModel : photoModelList) {
                switch (photoModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_REJECT:
                    case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        break;
                    default: {
                        final List<UploadFile> uploadFileList = new LinkedList<>();
                        try {
                            uploadFileList.addAll(uploadFileDao.queryBuilder()
                                    .where()
                                    .eq(UploadFile.PARENT_ID_FIELD, photoModel.getId())
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                    .query());
                        } catch (Exception e) {
                            Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                        }
                        boolean uploadFinish = true;
                        for (UploadFile uploadFile : uploadFileList) {
                            if (uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH && uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_PRE_UPLOAD_FINISH) {
                                uploadFinish = false;
                                break;
                            }
                        }
                        if (uploadFinish) {
                            if (photoModel.getRetryCount() > PublishUtil.MAX_PUBLISH_RETRY_NUM) {
                                try {
                                    UpdateBuilder<PhotoModel, String> updateBuilder = photoModelDao.updateBuilder();
                                    updateBuilder.updateColumnValue(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                    updateBuilder.updateColumnValue(PhotoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                                    updateBuilder.updateColumnValue(PhotoModel.RETRY_COUNT, 0);
                                    updateBuilder.where().eq(PhotoModel.ID, photoModel.getId());
                                    updateBuilder.update();
                                    photoModelDao.refresh(photoModel);
                                    shouldSendProgressStatusUpadteBroadcast = true;
                                } catch (Exception e) {

                                }
                                return;
                            }
                            try {
                                UpdateBuilder<PhotoModel, String> updateBuilder = photoModelDao.updateBuilder();
                                updateBuilder.updateColumnValue(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMITTING);
                                updateBuilder.where().eq(PhotoModel.ID, photoModel.getId());
                                updateBuilder.update();
                                photoModelDao.refresh(photoModel);
                                shouldSendProgressStatusUpadteBroadcast = true;
                            } catch (Exception e) {
                                Log.e(TAG, "handlePhotoPublish:" + Log.getStackTraceString(e));
                            }
                            //////////
                            final PhotoModel finalPhotoModel = photoModel;
                            /////////////////////////////
                            ApiManager.getService().oss().enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.OK) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                        if (ListUtil.isEmpty(ossList)) {
                                            throw new Exception("OSS 列表为空");
                                        }
                                        Oss oss = ossList.get(0);
                                        String photoDomain = oss.getImage().getDomain() + "/";
                                        String videoDomain = oss.getVideo().getDomain() + "/";
                                        List<SinglePhoto> photoList = new LinkedList<>();
                                        List<String> coverList = new LinkedList<>();
                                        for (UploadFile uploadFile : uploadFileList) {
                                            if (uploadFile.getFileType() == PublishUtil.UPLOAD_FILE_TYPE_PHOTO) {
                                                SinglePhoto singlePhoto = new SinglePhoto();
                                                singlePhoto.setTitle(uploadFile.getDescription());
                                                if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH) {
                                                    singlePhoto.setUrl(photoDomain + uploadFile.getStoreKey());
                                                } else {
                                                    singlePhoto.setUrl(uploadFile.getFileLocalUrl());
                                                }
                                                photoList.add(singlePhoto);
                                                coverList.add(singlePhoto.getUrl());
                                            }
                                        }
                                        List<TagBackup> tagList = new LinkedList<>();
                                        List<Interest> industryList = new LinkedList<>();
                                        try {
                                            industryList = JSON.parseArray(finalPhotoModel.getIndustry(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(industryList));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            List<Interest> interestList = JSON.parseArray(finalPhotoModel.getInterest(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(interestList));
                                        } catch (Exception e) {

                                        }


                                        Photo photo = new Photo();
                                        photo.setPhotos(photoList);
                                        photo.setPhotoCount(photoList.size());
                                        DetailBackup detailBackup = new DetailBackup();
                                        LocationData locationData = JSON.parseObject(finalPhotoModel.getLocation(), LocationData.class);
                                        Moment moment = new Moment();
                                        moment.setTags(tagList);
                                        moment.setCover(coverList);
                                        moment.setCreator(finalPhotoModel.getUserId());
                                        moment.setCityId(DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity()));
                                        moment.setTitle(finalPhotoModel.getTitle());
                                        moment.setMoreBackup(JSON.toJSONString(photo));
                                        moment.setCreateTime(finalPhotoModel.getReleaseDate());
                                        moment.setSubject(Moment.SUBJECT_PHOTO);
                                        moment.setSummary(finalPhotoModel.getIntroduction());
                                        moment.setDetailBackup(detailBackup);
                                        moment.setChannel(ListUtil.getFirstItem(industryList) == null ? "" : ListUtil.getFirstItem(industryList).getId());
                                        ///
                                        Call<ResponseBody> momentCall = ApiManager.getService().momentPublish(moment);
                                        momentCall.enqueue(new Callback<ResponseBody>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                try {
                                                    if (response.code() != ResponseCode.CREATED) {
                                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                    }
                                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                                    Moment respMoment = JSON.parseObject(json, Moment.class);
                                                    UpdateBuilder<PhotoModel, String> updateBuilder = photoModelDao.updateBuilder();
                                                    updateBuilder.updateColumnValue(PhotoModel.GOODS_ID, respMoment.getId());
                                                    updateBuilder.updateColumnValue(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED);
                                                    updateBuilder.updateColumnValue(PhotoModel.ROUTER, respMoment.getRouter());
                                                    updateBuilder.where().eq(PhotoModel.ID, finalPhotoModel.getId());
                                                    updateBuilder.update();
                                                    photoModelDao.refresh(finalPhotoModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    onFailure(call, e);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                Timber.e("onFailure:" + Log.getStackTraceString(t));
                                                try {
                                                    UpdateBuilder<PhotoModel, String> updateBuilder = photoModelDao.updateBuilder();
                                                    updateBuilder.updateColumnValue(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                                    updateBuilder.updateColumnValue(PhotoModel.RETRY_COUNT, finalPhotoModel.getRetryCount() + 1);
                                                    updateBuilder.where().eq(PhotoModel.ID, finalPhotoModel.getId());
                                                    updateBuilder.update();
                                                    photoModelDao.refresh(finalPhotoModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                                }
                                            }
                                        });
                                        ///////////////
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Timber.e("onFailure:" + Log.getStackTraceString(t));
                                    try {
                                        UpdateBuilder<PhotoModel, String> updateBuilder = photoModelDao.updateBuilder();
                                        updateBuilder.updateColumnValue(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                        updateBuilder.updateColumnValue(PhotoModel.RETRY_COUNT, finalPhotoModel.getRetryCount() + 1);
                                        updateBuilder.where().eq(PhotoModel.ID, finalPhotoModel.getId());
                                        updateBuilder.update();
                                        photoModelDao.refresh(finalPhotoModel);
                                        shouldSendProgressStatusUpadteBroadcast = true;
                                    } catch (Exception e) {
                                        Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                    }
                                }
                            });
                            ////////////////////////////

                        }
                        break;
                    }
                }
            }

        }

        public void handleNormalVideoPublish() {
            List<NormalVideoModel> normalVideoModelList = new LinkedList<>();
            try {
                normalVideoModelList = normalVideoModelDao.queryBuilder()
                        .where()
                        .eq(NormalVideoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_UPLOAD)
                        .and()
                        .eq(NormalVideoModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .query();
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (NormalVideoModel normalVideoModel : normalVideoModelList) {
                switch (normalVideoModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_REJECT:
                    case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        break;
                    default: {
                        final List<UploadFile> uploadFileList = new LinkedList<>();
                        try {
                            uploadFileList.addAll(uploadFileDao.queryBuilder()
                                    .where()
                                    .eq(UploadFile.PARENT_ID_FIELD, normalVideoModel.getId())
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                    .query());
                        } catch (Exception e) {
                            Log.e(TAG, "handleNormalVideoPublish:" + Log.getStackTraceString(e));
                        }
                        boolean uploadFinish = true;
                        for (UploadFile uploadFile : uploadFileList) {
                            if (uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH && uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_PRE_UPLOAD_FINISH) {
                                uploadFinish = false;
                                break;
                            }
                        }
                        if (uploadFinish) {
                            if (normalVideoModel.getRetryCount() > PublishUtil.MAX_PUBLISH_RETRY_NUM) {
                                try {
                                    UpdateBuilder<NormalVideoModel, String> updateBuilder = normalVideoModelDao.updateBuilder();
                                    updateBuilder.updateColumnValue(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                    updateBuilder.updateColumnValue(NormalVideoModel.RETRY_COUNT, 0);
                                    updateBuilder.updateColumnValue(NormalVideoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                                    updateBuilder.where().eq(NormalVideoModel.ID, normalVideoModel.getId());
                                    updateBuilder.update();
                                    normalVideoModelDao.refresh(normalVideoModel);
                                    shouldSendProgressStatusUpadteBroadcast = true;
                                } catch (Exception e) {

                                }
                                return;
                            }
                            try {
                                UpdateBuilder<NormalVideoModel, String> updateBuilder = normalVideoModelDao.updateBuilder();
                                updateBuilder.updateColumnValue(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMITTING);
                                updateBuilder.where().eq(NormalVideoModel.ID, normalVideoModel.getId());
                                updateBuilder.update();
                                normalVideoModelDao.refresh(normalVideoModel);
                                shouldSendProgressStatusUpadteBroadcast = true;
                            } catch (Exception e) {
                                Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                            }
                            //////////
                            final NormalVideoModel finalNormalVideoModel = normalVideoModel;
                            ////////////////////////////////
                            ApiManager.getService().oss().enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.OK) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                        if (ListUtil.isEmpty(ossList)) {
                                            throw new Exception("OSS 列表为空");
                                        }
                                        Oss oss = ossList.get(0);
                                        String photoDomain = oss.getImage().getDomain() + "/";
                                        String videoDomain = oss.getVideo().getDomain() + "/";
                                        List<SingleVideo> videoList = new LinkedList<>();
                                        for (UploadFile uploadFile : uploadFileList) {
                                            if (uploadFile.getFileType() == PublishUtil.UPLOAD_FILE_TYPE_VIDEO) {
                                                SingleVideo singleVideo = new SingleVideo();
                                                singleVideo.setPersistentId(uploadFile.getPersistentId());
                                                singleVideo.setTitle(uploadFile.getTitle());
                                                singleVideo.setDuration(uploadFile.getDuration());
                                                singleVideo.setFree(uploadFile.getBussinessType() != PublishUtil.BUSINESS_TYPE_PAID ? 1 : 0);
                                                singleVideo.setSize(uploadFile.getTotalSize());
                                                if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH) {
                                                    singleVideo.setUrl(videoDomain + uploadFile.getStoreKey());
                                                    singleVideo.setCover(photoDomain + uploadFile.getCoverStoreKey());
                                                } else {
                                                    singleVideo.setUrl(uploadFile.getFileLocalUrl());
                                                    singleVideo.setCover(uploadFile.getCoverUrl());
                                                }
                                                videoList.add(singleVideo);
                                            }
                                        }

                                        List<TagBackup> tagList = new LinkedList<>();
                                        List<Interest> industryList = new LinkedList<>();
                                        try {
                                            industryList = JSON.parseArray(finalNormalVideoModel.getIndustry(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(industryList));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            List<Interest> interestList = JSON.parseArray(finalNormalVideoModel.getInterest(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(interestList));
                                        } catch (Exception e) {

                                        }


                                        Video video = new Video();
                                        video.setVideos(videoList);
                                        DetailBackup detailBackup = new DetailBackup();
                                        LocationData locationData = JSON.parseObject(finalNormalVideoModel.getLocation(), LocationData.class);
                                        Moment moment = new Moment();
                                        moment.setTags(tagList);
                                        moment.setCreator(finalNormalVideoModel.getUserId());
                                        moment.setCityId(DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity()));
                                        moment.setTitle(finalNormalVideoModel.getTitle());
                                        moment.setCover(Arrays.asList(photoDomain + finalNormalVideoModel.getCoverStoreKey()));
                                        moment.setMoreBackup(JSON.toJSONString(video));
                                        moment.setCreateTime(finalNormalVideoModel.getReleaseDate());
                                        moment.setSubject(Moment.SUBJECT_VIDEO);
                                        moment.setSummary(finalNormalVideoModel.getIntroduction());
                                        moment.setDetailBackup(detailBackup);
                                        moment.setChannel(ListUtil.getFirstItem(industryList) == null ? "" : ListUtil.getFirstItem(industryList).getId());
                                        ///
                                        Call<ResponseBody> momentCall = ApiManager.getService().momentPublish(moment);
                                        momentCall.enqueue(new Callback<ResponseBody>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                try {
                                                    if (response.code() != ResponseCode.CREATED) {
                                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                    }
                                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                                    Moment respMoment = JSON.parseObject(json, Moment.class);
                                                    int progressStatus;
                                                    switch (respMoment.getStatus()) {
                                                        case Moment.STATUS_IN_REVIEW:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                                                            break;
                                                        case Moment.STATUS_REJECT:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                                                            break;
                                                        case Moment.STATUS_PUT_ON:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_SAVE:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_REVIEW_PASSED:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_GET_OFF:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_TRANSCODING:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                                                            break;
                                                        default:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                    }
                                                    UpdateBuilder<NormalVideoModel, String> updateBuilder = normalVideoModelDao.updateBuilder();
                                                    updateBuilder.updateColumnValue(NormalVideoModel.GOODS_ID, respMoment.getId());
                                                    updateBuilder.updateColumnValue(NormalVideoModel.PROGRESS_STATUS, progressStatus);
                                                    updateBuilder.updateColumnValue(NormalVideoModel.ROUTER, respMoment.getRouter());
                                                    updateBuilder.where().eq(NormalVideoModel.ID, finalNormalVideoModel.getId());
                                                    updateBuilder.update();
                                                    normalVideoModelDao.refresh(finalNormalVideoModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                    {
                                                        List<Long> videoSizeList = new LinkedList<>();
                                                        for (UploadFile uploadFile : uploadFileList) {
                                                            if (uploadFile.getFileType() == PublishUtil.UPLOAD_FILE_TYPE_VIDEO) {
                                                                videoSizeList.add(uploadFile.getTotalSize());
                                                            }
                                                        }
                                                        Map<String, String> sizeAttrs = new HashMap<>();
                                                        sizeAttrs.put("sizeArray", JSON.toJSONString(videoSizeList));
                                                        trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.PUBLISH_NORMAL_VIDEO_SIZE, TrackEvent.PUBLISH_NORMAL_VIDEO_SIZE_LABEL, sizeAttrs);
                                                        Map<String, String> numAttrs = new HashMap<>();
                                                        numAttrs.put("videoNum", String.valueOf(videoSizeList.size()));
                                                        trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.PUBLISH_NORMAL_VIDEO_NUM, TrackEvent.PUBLISH_NORMAL_VIDEO_NUM_LABEL, numAttrs);
                                                    }
                                                } catch (Exception e) {
                                                    onFailure(call, e);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                Timber.e("onFailure:" + Log.getStackTraceString(t));
                                                try {
                                                    UpdateBuilder<NormalVideoModel, String> updateBuilder = normalVideoModelDao.updateBuilder();
                                                    updateBuilder.updateColumnValue(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                                    updateBuilder.updateColumnValue(NormalVideoModel.RETRY_COUNT, finalNormalVideoModel.getRetryCount() + 1);
                                                    updateBuilder.where().eq(NormalVideoModel.ID, finalNormalVideoModel.getId());
                                                    updateBuilder.update();
                                                    normalVideoModelDao.refresh(finalNormalVideoModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                                }
                                            }
                                        });
                                        ///////////////
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Timber.e("onFailure:" + Log.getStackTraceString(t));
                                    try {
                                        UpdateBuilder<NormalVideoModel, String> updateBuilder = normalVideoModelDao.updateBuilder();
                                        updateBuilder.updateColumnValue(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                        updateBuilder.updateColumnValue(NormalVideoModel.RETRY_COUNT, finalNormalVideoModel.getRetryCount() + 1);
                                        updateBuilder.where().eq(NormalVideoModel.ID, finalNormalVideoModel.getId());
                                        updateBuilder.update();
                                        normalVideoModelDao.refresh(finalNormalVideoModel);
                                        shouldSendProgressStatusUpadteBroadcast = true;
                                    } catch (Exception e) {
                                        Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                    }
                                }
                            });
                        }
                        break;
                    }
                }
            }
        }


        public void handleSpecialTopicPublish() {
            List<SpecialTopicDBModel> specialTopicDBModelList = new LinkedList<>();
            try {
                specialTopicDBModelList = SpecialTopicDBModelDao.getDao().queryBuilder()
                        .where()
                        .eq(SpecialTopicDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_UPLOAD)
                        .and()
                        .eq(SpecialTopicDBModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .query();
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (SpecialTopicDBModel specialTopicDBModel : specialTopicDBModelList) {
                switch (specialTopicDBModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_REJECT:
                    case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        break;
                    default: {
                        final List<UploadFile> uploadFileList = new LinkedList<>();
                        try {
                            uploadFileList.addAll(uploadFileDao.queryBuilder()
                                    .where()
                                    .eq(UploadFile.PARENT_ID_FIELD, specialTopicDBModel.getId())
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                    .query());
                        } catch (Exception e) {
                            Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                        }
                        boolean uploadFinish = true;
                        for (UploadFile uploadFile : uploadFileList) {
                            if (uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH && uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_PRE_UPLOAD_FINISH) {
                                uploadFinish = false;
                                break;
                            }
                        }
                        if (uploadFinish) {
                            if (specialTopicDBModel.getRetryCount() > PublishUtil.MAX_PUBLISH_RETRY_NUM) {
                                try {
                                    UpdateBuilder<SpecialTopicDBModel, String> updateBuilder = SpecialTopicDBModelDao.getDao().updateBuilder();
                                    updateBuilder.updateColumnValue(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                    updateBuilder.updateColumnValue(SpecialTopicDBModel.RETRY_COUNT, 0);
                                    updateBuilder.updateColumnValue(SpecialTopicDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                                    updateBuilder.where().eq(SpecialTopicDBModel.ID, specialTopicDBModel.getId());
                                    updateBuilder.update();
                                    SpecialTopicDBModelDao.getDao().refresh(specialTopicDBModel);
                                    shouldSendProgressStatusUpadteBroadcast = true;
                                } catch (Exception e) {
                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                }
                                return;
                            }

                            try {
                                UpdateBuilder<SpecialTopicDBModel, String> updateBuilder = SpecialTopicDBModelDao.getDao().updateBuilder();
                                updateBuilder.updateColumnValue(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMITTING);
                                updateBuilder.where().eq(SpecialTopicDBModel.ID, specialTopicDBModel.getId());
                                updateBuilder.update();
                                SpecialTopicDBModelDao.getDao().refresh(specialTopicDBModel);
                                shouldSendProgressStatusUpadteBroadcast = true;
                            } catch (Exception e) {
                                Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                            }
                            //////////
                            final SpecialTopicDBModel finalSpecialTopicDBModel = specialTopicDBModel;
                            ////////////////////////////////////////////////////
                            ApiManager.getService().oss().enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.OK) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                        if (ListUtil.isEmpty(ossList)) {
                                            throw new Exception("OSS 列表为空");
                                        }
                                        Oss oss = ossList.get(0);
                                        String photoDomain = oss.getImage().getDomain() + "/";
                                        String videoDomain = oss.getVideo().getDomain() + "/";
                                        List<ArticleNode> articleNodeList = JSON.parseArray(finalSpecialTopicDBModel.getArticleJson(), ArticleNode.class);
                                        List<Content> contentList = PublishUtil.convertArticleToContent(photoDomain, videoDomain, articleNodeList);
                                        DetailBackup detailBackup = new DetailBackup();
                                        detailBackup.setContent(contentList);
                                        Article article = new Article();
                                        article.setRichText(RichTextUtil.handleRichTextContent(photoDomain, videoDomain, finalSpecialTopicDBModel.getRichText()));
                                        List<TagBackup> tagList = new LinkedList<>();

                                        List<Interest> industryList = new LinkedList<>();
                                        try {
                                            industryList = JSON.parseArray(finalSpecialTopicDBModel.getIndustry(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(industryList));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            List<Interest> interestList = JSON.parseArray(finalSpecialTopicDBModel.getInterest(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(interestList));
                                        } catch (Exception e) {

                                        }
                                        LocationData locationData = JSON.parseObject(finalSpecialTopicDBModel.getLocation(), LocationData.class);
                                        Moment moment = new Moment();
                                        moment.setTags(tagList);
                                        moment.setCreator(finalSpecialTopicDBModel.getUserId());
                                        moment.setCityId(DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity()));
                                        moment.setTitle(finalSpecialTopicDBModel.getTitle());
                                        moment.setCover(finalSpecialTopicDBModel.isCoverNeedUpload() ? Arrays.asList(photoDomain + finalSpecialTopicDBModel.getCoverStoreKey()) : Arrays.asList(finalSpecialTopicDBModel.getCoverUrl()));
                                        moment.setMoreBackup(JSON.toJSONString(article));
                                        moment.setCreateTime(finalSpecialTopicDBModel.getReleaseDate());
                                        moment.setSubject(Moment.SUBJECT_ARTICLE);
                                        moment.setSummary(finalSpecialTopicDBModel.getIntroduction());
                                        moment.setDetailBackup(detailBackup);
                                        moment.setChannel(ListUtil.getFirstItem(industryList) == null ? "" : ListUtil.getFirstItem(industryList).getId());
                                        ///
                                        Call<ResponseBody> momentCall;
                                        if (finalSpecialTopicDBModel.getPublishOperationType() == PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW) {
                                            momentCall = ApiManager.getService().momentPublish(moment);
                                        } else {
                                            momentCall = ApiManager.getService().editMoment(finalSpecialTopicDBModel.getGoodsId(), ActionEngine.PUBLISH, moment);
                                        }
                                        momentCall.enqueue(new Callback<ResponseBody>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                try {
                                                    if (response.code() != ResponseCode.CREATED) {
                                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                    }
                                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                                    Moment respMoment = JSON.parseObject(json, Moment.class);


                                                    int progressStatus;
                                                    switch (respMoment.getStatus()) {
                                                        case Moment.STATUS_IN_REVIEW:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                                                            break;
                                                        case Moment.STATUS_REJECT:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                                                            break;
                                                        case Moment.STATUS_PUT_ON:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_SAVE:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_REVIEW_PASSED:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_GET_OFF:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_TRANSCODING:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                                                            break;
                                                        default:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                    }


                                                    UpdateBuilder<SpecialTopicDBModel, String> updateBuilder = SpecialTopicDBModelDao.getDao().updateBuilder();
                                                    updateBuilder.updateColumnValue(SpecialTopicDBModel.GOODS_ID, respMoment.getId());
                                                    updateBuilder.updateColumnValue(SpecialTopicDBModel.PROGRESS_STATUS, progressStatus);
                                                    updateBuilder.updateColumnValue(SpecialTopicDBModel.ROUTER, respMoment.getRouter());
                                                    updateBuilder.where().eq(SpecialTopicDBModel.ID, finalSpecialTopicDBModel.getId());
                                                    updateBuilder.update();
                                                    SpecialTopicDBModelDao.getDao().refresh(finalSpecialTopicDBModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    onFailure(call, e);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                Timber.e("onFailure:" + Log.getStackTraceString(t));
                                                try {
                                                    UpdateBuilder<SpecialTopicDBModel, String> updateBuilder = SpecialTopicDBModelDao.getDao().updateBuilder();
                                                    updateBuilder.updateColumnValue(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                                    updateBuilder.updateColumnValue(SpecialTopicDBModel.RETRY_COUNT, finalSpecialTopicDBModel.getRetryCount() + 1);
                                                    updateBuilder.where().eq(SpecialTopicDBModel.ID, finalSpecialTopicDBModel.getId());
                                                    updateBuilder.update();
                                                    SpecialTopicDBModelDao.getDao().refresh(finalSpecialTopicDBModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                                }
                                            }
                                        });
                                        ///////////////
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Timber.e("onFailure:" + Log.getStackTraceString(t));
                                    try {
                                        UpdateBuilder<SpecialTopicDBModel, String> updateBuilder = SpecialTopicDBModelDao.getDao().updateBuilder();
                                        updateBuilder.updateColumnValue(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                        updateBuilder.updateColumnValue(SpecialTopicDBModel.RETRY_COUNT, finalSpecialTopicDBModel.getRetryCount() + 1);
                                        updateBuilder.where().eq(SpecialTopicDBModel.ID, finalSpecialTopicDBModel.getId());
                                        updateBuilder.update();
                                        SpecialTopicDBModelDao.getDao().refresh(finalSpecialTopicDBModel);
                                        shouldSendProgressStatusUpadteBroadcast = true;
                                    } catch (Exception e) {
                                        Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                    }
                                }
                            });
                            //////////////////////////////////////////////////////
                            //////////
                        }
                        break;
                    }
                }
            }
        }


        public void handleInfoPublish() {
            List<InfoModel> infoModelList = new LinkedList<>();
            try {
                infoModelList = infoModelDao.queryBuilder()
                        .where()
                        .eq(InfoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_UPLOAD)
                        .and()
                        .eq(InfoModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .query();
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (InfoModel infoModel : infoModelList) {
                switch (infoModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_REJECT:
                    case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        break;
                    default: {
                        final List<UploadFile> uploadFileList = new LinkedList<>();
                        try {
                            uploadFileList.addAll(uploadFileDao.queryBuilder()
                                    .where()
                                    .eq(UploadFile.PARENT_ID_FIELD, infoModel.getId())
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                    .query());
                        } catch (Exception e) {
                            Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                        }
                        boolean uploadFinish = true;
                        for (UploadFile uploadFile : uploadFileList) {
                            if (uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH && uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_PRE_UPLOAD_FINISH) {
                                uploadFinish = false;
                                break;
                            }
                        }
                        if (uploadFinish) {
                            if (infoModel.getRetryCount() > PublishUtil.MAX_PUBLISH_RETRY_NUM) {
                                try {
                                    UpdateBuilder<InfoModel, String> updateBuilder = infoModelDao.updateBuilder();
                                    updateBuilder.updateColumnValue(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                    updateBuilder.updateColumnValue(InfoModel.RETRY_COUNT, 0);
                                    updateBuilder.updateColumnValue(InfoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                                    updateBuilder.where().eq(InfoModel.ID, infoModel.getId());
                                    updateBuilder.update();
                                    infoModelDao.refresh(infoModel);
                                    shouldSendProgressStatusUpadteBroadcast = true;
                                } catch (Exception e) {
                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                }
                                return;
                            }

                            try {
                                UpdateBuilder<InfoModel, String> updateBuilder = infoModelDao.updateBuilder();
                                updateBuilder.updateColumnValue(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMITTING);
                                updateBuilder.where().eq(InfoModel.ID, infoModel.getId());
                                updateBuilder.update();
                                infoModelDao.refresh(infoModel);
                                shouldSendProgressStatusUpadteBroadcast = true;
                            } catch (Exception e) {
                                Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                            }
                            //////////
                            final InfoModel finalInfoModel = infoModel;
                            ////////////////////////////////////////////////////
                            ApiManager.getService().oss().enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.OK) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                        if (ListUtil.isEmpty(ossList)) {
                                            throw new Exception("OSS 列表为空");
                                        }
                                        Oss oss = ossList.get(0);
                                        String photoDomain = oss.getImage().getDomain() + "/";
                                        String videoDomain = oss.getVideo().getDomain() + "/";
                                        List<ArticleNode> articleNodeList = JSON.parseArray(finalInfoModel.getArticleJson(), ArticleNode.class);
                                        List<Content> contentList = PublishUtil.convertArticleToContent(photoDomain, videoDomain, articleNodeList);
                                        DetailBackup detailBackup = new DetailBackup();
                                        detailBackup.setContent(contentList);
                                        Article article = new Article();
                                        article.setRichText(RichTextUtil.handleRichTextContent(photoDomain, videoDomain, finalInfoModel.getRichText()));
                                        List<TagBackup> tagList = new LinkedList<>();

                                        List<Interest> industryList = new LinkedList<>();
                                        try {
                                            industryList = JSON.parseArray(finalInfoModel.getIndustry(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(industryList));
                                        } catch (Exception e) {

                                        }
                                        try {
                                            List<Interest> interestList = JSON.parseArray(finalInfoModel.getInterest(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(interestList));
                                        } catch (Exception e) {

                                        }
                                        LocationData locationData = JSON.parseObject(finalInfoModel.getLocation(), LocationData.class);
                                        Moment moment = new Moment();
                                        moment.setTags(tagList);
                                        moment.setCreator(finalInfoModel.getUserId());
                                        moment.setCityId(DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity()));
                                        moment.setTitle(finalInfoModel.getTitle());
                                        moment.setCover(finalInfoModel.isCoverNeedUpload() ? Arrays.asList(photoDomain + finalInfoModel.getCoverStoreKey()) : Arrays.asList(finalInfoModel.getCoverUrl()));
                                        moment.setMoreBackup(JSON.toJSONString(article));
                                        moment.setCreateTime(finalInfoModel.getReleaseDate());
                                        moment.setSubject(Moment.SUBJECT_ARTICLE);
                                        moment.setSummary(finalInfoModel.getIntroduction());
                                        moment.setDetailBackup(detailBackup);
                                        moment.setChannel(ListUtil.getFirstItem(industryList) == null ? "" : ListUtil.getFirstItem(industryList).getId());
                                        ///
                                        Call<ResponseBody> momentCall;
                                        if (finalInfoModel.getPublishOperationType() == PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW) {
                                            momentCall = ApiManager.getService().momentPublish(moment);
                                        } else {
                                            momentCall = ApiManager.getService().editMoment(finalInfoModel.getGoodsId(), ActionEngine.PUBLISH, moment);
                                        }
                                        momentCall.enqueue(new Callback<ResponseBody>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                try {
                                                    if (response.code() != ResponseCode.CREATED) {
                                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                    }
                                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                                    Moment respMoment = JSON.parseObject(json, Moment.class);


                                                    int progressStatus;
                                                    switch (respMoment.getStatus()) {
                                                        case Moment.STATUS_IN_REVIEW:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                                                            break;
                                                        case Moment.STATUS_REJECT:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                                                            break;
                                                        case Moment.STATUS_PUT_ON:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_SAVE:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_REVIEW_PASSED:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_GET_OFF:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_TRANSCODING:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                                                            break;
                                                        default:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                    }


                                                    UpdateBuilder<InfoModel, String> updateBuilder = infoModelDao.updateBuilder();
                                                    updateBuilder.updateColumnValue(InfoModel.GOODS_ID, respMoment.getId());
                                                    updateBuilder.updateColumnValue(InfoModel.PROGRESS_STATUS, progressStatus);
                                                    updateBuilder.updateColumnValue(InfoModel.ROUTER, respMoment.getRouter());
                                                    updateBuilder.where().eq(InfoModel.ID, finalInfoModel.getId());
                                                    updateBuilder.update();
                                                    infoModelDao.refresh(finalInfoModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    onFailure(call, e);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                Timber.e("onFailure:" + Log.getStackTraceString(t));
                                                try {
                                                    UpdateBuilder<InfoModel, String> updateBuilder = infoModelDao.updateBuilder();
                                                    updateBuilder.updateColumnValue(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                                    updateBuilder.updateColumnValue(InfoModel.RETRY_COUNT, finalInfoModel.getRetryCount() + 1);
                                                    updateBuilder.where().eq(InfoModel.ID, finalInfoModel.getId());
                                                    updateBuilder.update();
                                                    infoModelDao.refresh(finalInfoModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                                }
                                            }
                                        });
                                        ///////////////
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Timber.e("onFailure:" + Log.getStackTraceString(t));
                                    try {
                                        UpdateBuilder<InfoModel, String> updateBuilder = infoModelDao.updateBuilder();
                                        updateBuilder.updateColumnValue(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                        updateBuilder.updateColumnValue(InfoModel.RETRY_COUNT, finalInfoModel.getRetryCount() + 1);
                                        updateBuilder.where().eq(InfoModel.ID, finalInfoModel.getId());
                                        updateBuilder.update();
                                        infoModelDao.refresh(finalInfoModel);
                                        shouldSendProgressStatusUpadteBroadcast = true;
                                    } catch (Exception e) {
                                        Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                    }
                                }
                            });
                            //////////////////////////////////////////////////////
                            //////////
                        }
                        break;
                    }
                }
            }
        }


        public void handleLearnVideoPublish() {
            List<LearnVideoModel> learnVideoModelList = new LinkedList<>();
            try {
                learnVideoModelList = learnVideoModelDao.queryBuilder()
                        .where()
                        .eq(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_UPLOAD)
                        .and()
                        .eq(LearnVideoModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                        .query();
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (LearnVideoModel learnVideoModel : learnVideoModelList) {
                switch (learnVideoModel.getProgressStatus()) {
                    case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_REJECT:
                    case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        break;
                    default: {
                        final List<UploadFile> uploadFileList = new LinkedList<>();
                        try {
                            uploadFileList.addAll(
                                    uploadFileDao.queryBuilder().where()
                                            .eq(UploadFile.PARENT_ID_FIELD, learnVideoModel.getId())
                                            .and()
                                            .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                            .query());
                        } catch (Exception e) {
                            Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                        }
                        boolean uploadFinish = true;
                        for (UploadFile uploadFile : uploadFileList) {
                            if (uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH && uploadFile.getProgressStatus() != PublishUtil.PROGRESS_STATUS_PRE_UPLOAD_FINISH) {
                                uploadFinish = false;
                                break;
                            }
                        }
                        if (uploadFinish) {
                            if (learnVideoModel.getRetryCount() > PublishUtil.MAX_PUBLISH_RETRY_NUM) {
                                try {
                                    UpdateBuilder<LearnVideoModel, String> updateBuilder = learnVideoModelDao.updateBuilder();
                                    updateBuilder.updateColumnValue(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                    updateBuilder.updateColumnValue(LearnVideoModel.RETRY_COUNT_FIELD, 0);
                                    updateBuilder.updateColumnValue(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                                    updateBuilder.where().eq(LearnVideoModel.ID_FIELD, learnVideoModel.getId());
                                    updateBuilder.update();
                                    learnVideoModelDao.refresh(learnVideoModel);
                                    shouldSendProgressStatusUpadteBroadcast = true;
                                    trackEvent.sendEvent(getApplicationContext(), TrackEvent.LEARN_VIDEO_PUBLISH_FAILED, TrackEvent.LEARN_VIDEO_PUBLISH_FAILED_LABEL);
                                } catch (Exception e) {

                                }
                                return;
                            }
                            try {
                                UpdateBuilder<LearnVideoModel, String> updateBuilder = learnVideoModelDao.updateBuilder();
                                updateBuilder.updateColumnValue(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMITTING);
                                updateBuilder.where().eq(LearnVideoModel.ID_FIELD, learnVideoModel.getId());
                                updateBuilder.update();
                                learnVideoModelDao.refresh(learnVideoModel);
                                shouldSendProgressStatusUpadteBroadcast = true;
                            } catch (Exception e) {
                                Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                            }
                            //////////
                            final LearnVideoModel finalLearnVideoModel = learnVideoModel;
                            ApiManager.getService().oss().enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.OK) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                        if (ListUtil.isEmpty(ossList)) {
                                            throw new Exception("OSS 列表为空");
                                        }
                                        Oss oss = ossList.get(0);
                                        String photoDomain = oss.getImage().getDomain() + "/";
                                        String videoDomain = oss.getVideo().getDomain() + "/";
                                        List<SingleVideo> videoList = new LinkedList<>();
                                        for (UploadFile uploadFile : uploadFileList) {
                                            if (uploadFile.getFileType() == PublishUtil.UPLOAD_FILE_TYPE_VIDEO) {
                                                SingleVideo singleVideo = new SingleVideo();
                                                singleVideo.setPersistentId(uploadFile.getPersistentId());
                                                singleVideo.setTitle(uploadFile.getTitle());
                                                singleVideo.setDuration(uploadFile.getDuration());
                                                singleVideo.setFree(uploadFile.getBussinessType() != PublishUtil.BUSINESS_TYPE_PAID ? 1 : 0);
                                                singleVideo.setSize(uploadFile.getTotalSize());
                                                if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH) {
                                                    singleVideo.setUrl(videoDomain + uploadFile.getStoreKey());
                                                    singleVideo.setCover(photoDomain + uploadFile.getCoverStoreKey());
                                                } else {
                                                    singleVideo.setUrl(uploadFile.getFileLocalUrl());
                                                    singleVideo.setCover(uploadFile.getCoverUrl());
                                                }
                                                videoList.add(singleVideo);
                                            }
                                        }

                                        List<Guarantee> guaranteeList = new LinkedList<>();
                                        List<GuaranteeItem> guaranteeItemList = JSON.parseArray(finalLearnVideoModel.getGuarantee(), GuaranteeItem.class);
                                        for (GuaranteeItem guaranteeItem : guaranteeItemList) {
                                            if (TextUtils.isEmpty(guaranteeItem.getId())) continue;
                                            Guarantee guarantee = new Guarantee();
                                            guarantee.setId(guaranteeItem.getId());
                                            guarantee.setDetail(guaranteeItem.getContent());
                                            guarantee.setName(guaranteeItem.getTitle());
                                            guaranteeList.add(guarantee);
                                        }
                                        List<TagBackup> tagList = new LinkedList<>();
                                        ////////////////
                                        ///
                                        try {
                                            List<Interest> interestList = JSON.parseArray(finalLearnVideoModel.getInterest(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(interestList));
                                        } catch (Exception e) {

                                        }

                                        List<Interest> industryList = new LinkedList<>();
                                        try {
                                            industryList = JSON.parseArray(finalLearnVideoModel.getIndustry(), Interest.class);
                                            tagList.addAll(InterestUtil.convertInterestListToTagBackupList(industryList));
                                        } catch (Exception e) {

                                        }


                                        VideoCourse videoCourse = new VideoCourse();
                                        try {
                                            videoCourse.setDivisionProportion(Double.parseDouble(finalLearnVideoModel.getPlatformDividend()) / 100);
                                        } catch (Exception e) {

                                        }
                                        videoCourse.setVideos(videoList);
                                        DetailBackup detailBackup = new DetailBackup();
                                        detailBackup.setGuarantee(guaranteeList);
                                        videoCourse.setPrice(finalLearnVideoModel.getPrice());
                                        videoCourse.setOriginPrice(finalLearnVideoModel.getPrice());
                                        videoCourse.setApplePriceId(finalLearnVideoModel.getPriceId());
                                        videoCourse.setServicePhone(AccountUtil.getCurrentUser().getMobile());
                                        videoCourse.setTeacher(finalLearnVideoModel.getTeacher());
                                        videoCourse.setLearningGoals(finalLearnVideoModel.getLearnTarget());
                                        videoCourse.setCourseType(finalLearnVideoModel.getCourseType());
                                        videoCourse.setSuitablePopulation(finalLearnVideoModel.getSuitablePeople());
                                        LocationData locationData = JSON.parseObject(finalLearnVideoModel.getLocation(), LocationData.class);
                                        Moment moment = new Moment();
                                        moment.setTags(tagList);
                                        moment.setCreator(finalLearnVideoModel.getUserId());
                                        moment.setCityId(DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity()));
                                        moment.setTitle(finalLearnVideoModel.getTitle());
                                        moment.setCover(Arrays.asList(photoDomain + finalLearnVideoModel.getCoverStoreKey()));
                                        moment.setMoreBackup(JSON.toJSONString(videoCourse));
                                        moment.setCreateTime(finalLearnVideoModel.getReleaseDate());
                                        moment.setSubject(Moment.SUBJECT_VIDEO_COURSE);
                                        moment.setSummary(finalLearnVideoModel.getIntroduction());
                                        moment.setDetailBackup(detailBackup);
                                        moment.setChannel(ListUtil.getFirstItem(industryList) == null ? "" : ListUtil.getFirstItem(industryList).getId());
                                        ///
                                        Call<ResponseBody> momentCall;
                                        if (finalLearnVideoModel.getPublishOperationType() == PublishUtil.PUBLISH_OPERATION_TYPE_SAVE) {
                                            momentCall = ApiManager.getService().momentSaveOnly(moment);
                                        } else if (finalLearnVideoModel.getPublishOperationType() == PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW) {
                                            momentCall = ApiManager.getService().momentPublish(moment);
                                        } else if (finalLearnVideoModel.getPublishOperationType() == PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE) {
                                            momentCall = ApiManager.getService().editMoment(finalLearnVideoModel.getGoodsId(), ActionEngine.SAVE, moment);
                                        } else {
                                            momentCall = ApiManager.getService().editMoment(finalLearnVideoModel.getGoodsId(), ActionEngine.PUBLISH, moment);
                                        }
                                        momentCall.enqueue(new Callback<ResponseBody>() {
                                            @Override
                                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                try {
                                                    if (response.code() != ResponseCode.CREATED) {
                                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                    }
                                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                                    Moment respMoment = JSON.parseObject(json, Moment.class);
                                                    UpdateBuilder<LearnVideoModel, String> updateBuilder = learnVideoModelDao.updateBuilder();
                                                    updateBuilder.updateColumnValue(LearnVideoModel.GOODS_ID_FIELD, respMoment.getId());
                                                    updateBuilder.updateColumnValue(LearnVideoModel.ROUTER_FIELD, respMoment.getRouter());
                                                    int progressStatus;
                                                    switch (respMoment.getStatus()) {
                                                        case Moment.STATUS_IN_REVIEW:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                                                            break;
                                                        case Moment.STATUS_REJECT:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                                                            break;
                                                        case Moment.STATUS_PUT_ON:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_SAVE:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_REVIEW_PASSED:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_GET_OFF:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                        case Moment.STATUS_TRANSCODING:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                                                            break;
                                                        default:
                                                            progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                                            break;
                                                    }
                                                    updateBuilder.updateColumnValue(LearnVideoModel.PROGRESS_STATUS_FIELD, progressStatus);
                                                    updateBuilder.where().eq(LearnVideoModel.ID_FIELD, finalLearnVideoModel.getId());
                                                    updateBuilder.update();
                                                    learnVideoModelDao.refresh(finalLearnVideoModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                    trackEvent.sendEvent(getApplicationContext(), TrackEvent.LEARN_VIDEO_PUBLISH_FINISH, TrackEvent.LEARN_VIDEO_PUBLISH_FINISH_LABEL);
                                                    {
                                                        Map<String, String> attrs = new HashMap<>();
                                                        attrs.put("duration", String.valueOf(System.currentTimeMillis() - finalLearnVideoModel.getReleaseDate()));
                                                        trackEvent.sendEvent(getApplicationContext(), TrackEvent.LEARN_VIDEO_PUBLISH_DURATION, TrackEvent.LEARN_VIDEO_PUBLISH_DURATION_LABEL, attrs);
                                                    }
                                                } catch (Exception e) {
                                                    onFailure(call, e);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                Timber.e("onFailure:" + Log.getStackTraceString(t));
                                                try {
                                                    UpdateBuilder<LearnVideoModel, String> updateBuilder = learnVideoModelDao.updateBuilder();
                                                    updateBuilder.updateColumnValue(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                                    updateBuilder.updateColumnValue(LearnVideoModel.RETRY_COUNT_FIELD, finalLearnVideoModel.getRetryCount() + 1);
                                                    updateBuilder.where().eq(LearnVideoModel.ID_FIELD, finalLearnVideoModel.getId());
                                                    updateBuilder.update();
                                                    learnVideoModelDao.refresh(finalLearnVideoModel);
                                                    shouldSendProgressStatusUpadteBroadcast = true;
                                                } catch (Exception e) {
                                                    Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                                }
                                            }
                                        });
                                        ///////////////
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Timber.e("onFailure:" + Log.getStackTraceString(t));
                                    try {
                                        UpdateBuilder<LearnVideoModel, String> updateBuilder = learnVideoModelDao.updateBuilder();
                                        updateBuilder.updateColumnValue(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED);
                                        updateBuilder.updateColumnValue(LearnVideoModel.RETRY_COUNT_FIELD, finalLearnVideoModel.getRetryCount() + 1);
                                        updateBuilder.where().eq(LearnVideoModel.ID_FIELD, finalLearnVideoModel.getId());
                                        updateBuilder.update();
                                        learnVideoModelDao.refresh(finalLearnVideoModel);
                                        shouldSendProgressStatusUpadteBroadcast = true;
                                    } catch (Exception e) {
                                        Log.e(TAG, "handleLearnVideoPublish:" + Log.getStackTraceString(e));
                                    }
                                }
                            });
                            //////////
                        }
                        break;
                    }
                }
            }
        }


        public void handleDelete() {
            try {
                List<UploadFile> uploadFileList = uploadFileDao.queryForEq(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                for (UploadFile uploadFile : uploadFileList) {
                    try {
                        if (uploadFile.getId() == currentTranscodingFile.getId()) {
                            transcoderUtils.exit();
                            currentTranscodingFile = null;
                        }
                    } catch (Exception e) {

                    }
                    uploadFileDao.deleteById(uploadFile.getId());
                    shouldSendProgressStatusUpadteBroadcast = true;
                    shouldSendUploadUpdateBroadcast = true;
                }
            } catch (Exception e) {
                Log.e(TAG, "handleDelete:" + Log.getStackTraceString(e));
            }
            try {
                List<LearnVideoModel> learnVideoModelList = learnVideoModelDao.queryForEq(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                for (LearnVideoModel learnVideoModel : learnVideoModelList) {
                    learnVideoModelDao.deleteById(learnVideoModel.getId());
                    shouldSendProgressStatusUpadteBroadcast = true;
                    shouldSendUploadUpdateBroadcast = true;
                }
            } catch (Exception e) {
                Log.e(TAG, "handleDelete:" + Log.getStackTraceString(e));
            }
            try {
                List<PhotoModel> photoModelList = photoModelDao.queryForEq(PhotoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_DELETE);
                for (PhotoModel photoModel : photoModelList) {
                    photoModelDao.deleteById(photoModel.getId());
                    shouldSendProgressStatusUpadteBroadcast = true;
                    shouldSendUploadUpdateBroadcast = true;
                }
            } catch (Exception e) {
                Log.e(TAG, "handleDelete:" + Log.getStackTraceString(e));
            }

            try {
                List<InfoModel> infoModelList = infoModelDao.queryForEq(InfoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_DELETE);
                for (InfoModel infoModel : infoModelList) {
                    infoModelDao.deleteById(infoModel.getId());
                    shouldSendProgressStatusUpadteBroadcast = true;
                    shouldSendUploadUpdateBroadcast = true;
                }
            } catch (Exception e) {
                Log.e(TAG, "handleDelete:" + Log.getStackTraceString(e));
            }

            try {
                List<NormalVideoModel> normalVideoModelList = normalVideoModelDao.queryForEq(NormalVideoModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_DELETE);
                for (NormalVideoModel normalVideoModel : normalVideoModelList) {
                    normalVideoModelDao.deleteById(normalVideoModel.getId());
                    shouldSendProgressStatusUpadteBroadcast = true;
                    shouldSendUploadUpdateBroadcast = true;
                }
            } catch (Exception e) {
                Log.e(TAG, "handleDelete:" + Log.getStackTraceString(e));
            }
            try {
                DeleteBuilder<MajorCourseDBModel, String> deleteBuilder = MajorCourseDBModelDao.getDao().deleteBuilder();
                deleteBuilder.where().eq(MajorCourseDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_DELETE);
                deleteBuilder.delete();
                shouldSendProgressStatusUpadteBroadcast = true;
                shouldSendUploadUpdateBroadcast = true;
            } catch (Exception e) {
                Log.e(TAG, "handleDelete:" + Log.getStackTraceString(e));
            }
            try {
                DeleteBuilder<TraingClassDBModel, String> deleteBuilder = TraingClassDBModelDao.getDao().deleteBuilder();
                deleteBuilder.where().eq(TraingClassDBModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                deleteBuilder.delete();
                shouldSendProgressStatusUpadteBroadcast = true;
                shouldSendUploadUpdateBroadcast = true;
            } catch (Exception e) {
                Log.e(TAG, "handleDelete:" + Log.getStackTraceString(e));
            }
            try {
                DeleteBuilder<TraingCardDBModel, String> deleteBuilder = TraingCardDBModelDao.getDao().deleteBuilder();
                deleteBuilder.where().eq(TraingCardDBModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                deleteBuilder.delete();
                shouldSendProgressStatusUpadteBroadcast = true;
                shouldSendUploadUpdateBroadcast = true;
            } catch (Exception e) {
                Log.e(TAG, "handleDelete:" + Log.getStackTraceString(e));
            }

        }

        public boolean checkFinish() {
            try {
                List<MajorCourseDBModel> majorCourseDBModelList = MajorCourseDBModelDao.getDao().queryBuilder()
                        .where()
                        .eq(MajorCourseDBModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .and()
                        .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                        .and()
                        .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                        .and()
                        .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                        .and()
                        .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                        .and()
                        .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                        .query();
                if (!majorCourseDBModelList.isEmpty()) {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "checkFinish:" + Log.getStackTraceString(e));
            }
            try {
                List<TraingClassDBModel> traingClassDBModelList = TraingClassDBModelDao.getDao().queryBuilder()
                        .where()
                        .eq(TraingClassDBModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                        .and()
                        .ne(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT)
                        .and()
                        .ne(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                        .and()
                        .ne(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                        .and()
                        .ne(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                        .and()
                        .ne(TraingClassDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                        .query();
                if (!traingClassDBModelList.isEmpty()) {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "checkFinish:" + Log.getStackTraceString(e));
            }

            try {
                List<TraingCardDBModel> traingCardDBModelList = TraingCardDBModelDao.getDao().queryBuilder()
                        .where()
                        .eq(TraingCardDBModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                        .and()
                        .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT)
                        .and()
                        .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                        .and()
                        .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                        .and()
                        .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                        .and()
                        .ne(TraingCardDBModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                        .query();
                if (!traingCardDBModelList.isEmpty()) {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "checkFinish:" + Log.getStackTraceString(e));
            }
            try {
                List<LearnVideoModel> learnVideoModelList = learnVideoModelDao.queryBuilder()
                        .where()
                        .eq(LearnVideoModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                        .and()
                        .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT)
                        .and()
                        .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                        .and()
                        .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                        .and()
                        .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                        .and()
                        .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                        .query();
                if (!learnVideoModelList.isEmpty()) {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "checkFinish:" + Log.getStackTraceString(e));
            }
            try {
                List<PhotoModel> photoModelList = photoModelDao.queryBuilder()
                        .where()
                        .eq(PhotoModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .and()
                        .ne(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                        .and()
                        .ne(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                        .and()
                        .ne(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                        .and()
                        .ne(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                        .and()
                        .ne(PhotoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                        .query();
                if (!photoModelList.isEmpty()) {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "checkFinish:" + Log.getStackTraceString(e));
            }

            try {
                List<InfoModel> infoModelList = infoModelDao.queryBuilder()
                        .where()
                        .eq(InfoModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .and()
                        .ne(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                        .and()
                        .ne(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                        .and()
                        .ne(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                        .and()
                        .ne(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                        .and()
                        .ne(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                        .query();
                if (!infoModelList.isEmpty()) {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "checkFinish:" + Log.getStackTraceString(e));
            }

            try {
                List<NormalVideoModel> normalVideoModelList = normalVideoModelDao.queryBuilder()
                        .where()
                        .eq(NormalVideoModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .and()
                        .ne(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                        .and()
                        .ne(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                        .and()
                        .ne(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                        .and()
                        .ne(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                        .and()
                        .ne(NormalVideoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                        .query();
                if (!normalVideoModelList.isEmpty()) {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "checkFinish:" + Log.getStackTraceString(e));
            }


            try {
                List<SpecialTopicDBModel> specialTopicDBModelList = SpecialTopicDBModelDao.getDao().queryBuilder()
                        .where()
                        .eq(SpecialTopicDBModel.USER_ID, AccountUtil.getCurrentUser().getId())
                        .and()
                        .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                        .and()
                        .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                        .and()
                        .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                        .and()
                        .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                        .and()
                        .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                        .query();
                if (!specialTopicDBModelList.isEmpty()) {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, "checkFinish:" + Log.getStackTraceString(e));
            }
            return true;
        }

        public void retryUploadFile(final UploadFile uploadFile) {
            if (uploadFile.getRetryCount() > PublishUtil.MAX_UPLOAD_RETRY_NUM) {
                try {
                    UpdateBuilder<UploadFile, Integer> updateBuilder = uploadFileDao.updateBuilder();
                    updateBuilder.updateColumnValue(UploadFile.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_UPLOADING);
                    updateBuilder.updateColumnValue(UploadFile.RETRY_COUNT_FIELD, 0);
                    updateBuilder.updateColumnValue(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_FAILED_PAUSE);
                    updateBuilder.where().eq(UploadFile.ID_FIELD, uploadFile.getId());
                    updateBuilder.update();
                    uploadFileDao.refresh(uploadFile);
                    PublishUtil.sendUploadUpdateBroadcast();
                } catch (Exception e) {
                    Timber.e("retryUploadFile:" + Log.getStackTraceString(e));
                }
                return;
            }
            try {
                UpdateBuilder<UploadFile, Integer> updateBuilder = uploadFileDao.updateBuilder();
                updateBuilder.updateColumnValue(UploadFile.UPLOAD_TIMESTAMP_FIELD, System.currentTimeMillis());
                updateBuilder.updateColumnValue(UploadFile.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_UPLOADING);
                updateBuilder.updateColumnValue(UploadFile.RETRY_COUNT_FIELD, uploadFile.getRetryCount() + 1);
                updateBuilder.where().eq(UploadFile.ID_FIELD, uploadFile.getId());
                updateBuilder.update();
                uploadFileDao.refresh(uploadFile);
            } catch (Exception e) {
                Log.e(TAG, "retryUploadFile:" + Log.getStackTraceString(e));
            }
            ApiManager.getService()
                    .oss(uploadFile.getStoreKey())
                    .enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            try {
                                if (response.code() != ResponseCode.OK) {
                                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                }
                                String json = RetrofitUtil.getResponseBodyAsString(response);
                                List<Oss> ossList = JSON.parseArray(json, Oss.class);
                                if (ListUtil.isEmpty(ossList)) {
                                    throw new Exception("OSS列表为空");
                                }
                                Oss oss = ossList.get(0);
                                {
                                    String token = "";
                                    if (uploadFile.getFileType() == PublishUtil.UPLOAD_FILE_TYPE_PHOTO) {
                                        token = oss.getImage().getToken().getToken();
                                    } else {
                                        token = oss.getVideo().getToken().getToken();
                                    }
                                    doUpload(token, uploadFile);
                                }
                            } catch (Exception e) {
                                onFailure(call, e);
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Log.e(TAG, "onFailure:" + Log.getStackTraceString(t));
                        }
                    });
        }


        public void doUpload(String token, final UploadFile uploadFile) {
            if (!RxFileTool.isFile(uploadFile.getFileLocalUrl())) {
                try {
                    uploadFileDao.delete(uploadFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
            if (myUpCancellationSignalMap.containsKey(uploadFile.getStoreKey())) {
                MyUpCancellationSingal myUpCancellationSingal = myUpCancellationSignalMap.get(uploadFile.getStoreKey());
                myUpCancellationSingal.setForceCancel(true);
                myUpCancellationSignalMap.remove(uploadFile.getStoreKey());
            }
            MyUpCancellationSingal myUpCancellationSingal = new MyUpCancellationSingal() {
                @Override
                boolean checkCancel() {
                    boolean shouldCancelled;
                    try {
                        UploadFile tempUploadFile = uploadFileDao.queryForId(uploadFile.getId());
                        shouldCancelled = tempUploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH || tempUploadFile.getControlOption() == PublishUtil.CONTROL_OPTION_PAUSE || uploadFile.getControlOption() == PublishUtil.CONTROL_OPTION_DELETE;
                    } catch (Exception e) {
                        shouldCancelled = true;
                    }
                    return shouldCancelled;
                }
            };
            myUpCancellationSignalMap.put(uploadFile.getStoreKey(), myUpCancellationSingal);
            UploadOptions uploadOptions = new UploadOptions(
                    null,
                    null,
                    false,
                    new UpProgressHandler() {
                        long progressTimestamp = 0;

                        @Override
                        public void progress(String key, double percent) {
                            Timber.e("progress:" + percent + "storeKey:" + uploadFile.getStoreKey());
                            if ((System.currentTimeMillis() - progressTimestamp) > 500) {
                                progressTimestamp = System.currentTimeMillis();
                                try {
                                    UpdateBuilder<UploadFile, Integer> updateBuilder = uploadFileDao.updateBuilder();
                                    updateBuilder.updateColumnValue(UploadFile.UPLOADED_SIZE_FIELD, (long) (uploadFile.getTotalSize() * percent));
                                    updateBuilder.updateColumnValue(UploadFile.UPLOAD_TIMESTAMP_FIELD, System.currentTimeMillis());
                                    updateBuilder.where().eq(UploadFile.ID_FIELD, uploadFile.getId());
                                    updateBuilder.update();
                                    uploadFileDao.refresh(uploadFile);
                                } catch (Exception e) {
                                    Log.e(TAG, "progress:" + Log.getStackTraceString(e));
                                }
                                shouldSendUploadUpdateBroadcast = true;
                            }
                        }
                    },
                    myUpCancellationSingal);
            UpCompletionHandler upCompletionHandler = new UpCompletionHandler() {
                @Override
                public void complete(String key, ResponseInfo info, JSONObject response) {
                    if (info.isOK()) {
                        try {
                            UpdateBuilder<UploadFile, Integer> updateBuilder = uploadFileDao.updateBuilder();
                            updateBuilder.updateColumnValue(UploadFile.PERSISTENET_ID_FIELD, response.getString("persistentId"));
                            updateBuilder.updateColumnValue(UploadFile.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH);
                            updateBuilder.updateColumnValue(UploadFile.UPLOADED_SIZE_FIELD, uploadFile.getTotalSize());
                            updateBuilder.where().eq(UploadFile.ID_FIELD, uploadFile.getId());
                            updateBuilder.update();
                            uploadFileDao.refresh(uploadFile);
                        } catch (Exception e) {
                            Log.e(TAG, "complete:" + Log.getStackTraceString(e));
                        }
                        shouldSendUploadUpdateBroadcast = true;
                    }
                }
            };

            uploadManager.put(
                    uploadFile.getFileLocalUrl(),
                    uploadFile.getStoreKey(),
                    token,
                    upCompletionHandler,
                    uploadOptions);
        }


        public void shutdown() {
            try {
                transcoderUtils.exit();
            } catch (Exception e) {

            }
            mutex.lock();
            stopWork = true;
            waitCondition.signalAll();
            mutex.unlock();
            try {
                join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(String error) {
            Timber.e("failed:transcode failed");
            try {
                UpdateBuilder<UploadFile, Integer> updateBuilder = uploadFileDao.updateBuilder();
                updateBuilder.updateColumnValue(UploadFile.TRANSCODE_PROGRESS_FIELD, 0);
                updateBuilder.updateColumnValue(UploadFile.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE);
                updateBuilder.where().eq(UploadFile.ID_FIELD, currentTranscodingFile.getId());
                updateBuilder.update();
                uploadFileDao.refresh(currentTranscodingFile);
            } catch (Exception e) {
                Log.e(TAG, "failed:" + Log.getStackTraceString(e));
            }
            shouldSendTranscodeUpdateBroadcast = true;
            currentTranscodingFile = null;
        }

        @Override
        public void cancel() {

        }

        @Override
        public void finish(String path) {
            Log.e(TAG, "finish:" + path);
            switch (currentTranscodingFile.getParentType()) {
                case PublishUtil.PARENT_TYPE_LEARN_VIDEO: {
                    List<UploadFile> uploadFileList = new LinkedList<>();
                    try {
                        uploadFileList = uploadFileDao.queryForEq(UploadFile.PARENT_ID_FIELD, currentTranscodingFile.getParentId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int progressStatus = PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH;
                    for (UploadFile uploadFile : uploadFileList) {
                        if (uploadFile.getId() == currentTranscodingFile.getId()) continue;
                        if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE) {
                            progressStatus = PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE;
                            break;
                        }
                        if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED) {
                            progressStatus = PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED;
                            break;
                        }
                    }
                    try {
                        LearnVideoModel learnVideoModel = learnVideoModelDao.queryForId(currentTranscodingFile.getParentId());
                        UpdateBuilder<LearnVideoModel, String> updateBuilder = learnVideoModelDao.updateBuilder();
                        updateBuilder.updateColumnValue(LearnVideoModel.PROGRESS_STATUS_FIELD, progressStatus);
                        updateBuilder.where().eq(LearnVideoModel.ID_FIELD, learnVideoModel.getId());
                        updateBuilder.update();
                    } catch (Exception e) {
                        Log.e(TAG, "finish:" + Log.getStackTraceString(e));
                    }
                    break;
                }
                case PublishUtil.PARENT_TYPE_INFO: {
                    List<UploadFile> uploadFileList = new LinkedList<>();
                    try {
                        uploadFileList = uploadFileDao.queryForEq(UploadFile.PARENT_ID_FIELD, currentTranscodingFile.getParentId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int progressStatus = PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH;
                    for (UploadFile uploadFile : uploadFileList) {
                        if (uploadFile.getId() == currentTranscodingFile.getId()) continue;
                        if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE) {
                            progressStatus = PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE;
                            break;
                        }
                        if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED) {
                            progressStatus = PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED;
                            break;
                        }
                    }
                    try {
                        InfoModel infoModel = infoModelDao.queryForId(currentTranscodingFile.getParentId());
                        UpdateBuilder<InfoModel, String> updateBuilder = infoModelDao.updateBuilder();
                        updateBuilder.updateColumnValue(InfoModel.PROGRESS_STATUS, progressStatus);
                        updateBuilder.where().eq(InfoModel.ID, infoModel.getId());
                        updateBuilder.update();
                    } catch (Exception e) {
                        Log.e(TAG, "finish:" + Log.getStackTraceString(e));
                    }
                    break;
                }
                case PublishUtil.PARENT_TYPE_NORMAL_VIDEO: {
                    List<UploadFile> uploadFileList = new LinkedList<>();
                    try {
                        uploadFileList = uploadFileDao.queryForEq(UploadFile.PARENT_ID_FIELD, currentTranscodingFile.getParentId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int progressStatus = PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH;
                    for (UploadFile uploadFile : uploadFileList) {
                        if (uploadFile.getId() == currentTranscodingFile.getId()) continue;
                        if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE) {
                            progressStatus = PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE;
                            break;
                        }
                        if (uploadFile.getProgressStatus() == PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED) {
                            progressStatus = PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED;
                            break;
                        }
                    }
                    try {
                        NormalVideoModel normalVideoModel = normalVideoModelDao.queryForId(currentTranscodingFile.getParentId());
                        UpdateBuilder<NormalVideoModel, String> updateBuilder = normalVideoModelDao.updateBuilder();
                        updateBuilder.updateColumnValue(NormalVideoModel.PROGRESS_STATUS, progressStatus);
                        updateBuilder.where().eq(NormalVideoModel.ID, normalVideoModel.getId());
                        updateBuilder.update();
                    } catch (Exception e) {
                        Log.e(TAG, "finish:" + Log.getStackTraceString(e));
                    }
                    break;
                }
                default:
                    break;
            }
            try {
                UpdateBuilder<UploadFile, Integer> updateBuilder = uploadFileDao.updateBuilder();
                updateBuilder.updateColumnValue(UploadFile.TRANSCODE_PROGRESS_FIELD, 100);
                updateBuilder.updateColumnValue(UploadFile.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH);
                updateBuilder.updateColumnValue(UploadFile.FILE_LOCAL_URL, path);
                updateBuilder.updateColumnValue(UploadFile.TOTAL_SIZE, FileUtil.getFileSize(path));
                updateBuilder.where().eq(UploadFile.ID_FIELD, currentTranscodingFile.getId());
                updateBuilder.update();
                uploadFileDao.refresh(currentTranscodingFile);
            } catch (Exception e) {
                Log.e(TAG, "finish:" + Log.getStackTraceString(e));
            }
            shouldSendTranscodeUpdateBroadcast = true;
            currentTranscodingFile = null;
        }

        @Override
        public void progress(int progress) {
            Timber.e("progress:transcode progress" + progress);
            try {
                UpdateBuilder<UploadFile, Integer> updateBuilder = uploadFileDao.updateBuilder();
                updateBuilder.updateColumnValue(UploadFile.TRANSCODE_PROGRESS_FIELD, progress);
                updateBuilder.where().eq(UploadFile.ID_FIELD, currentTranscodingFile.getId());
                updateBuilder.update();
                uploadFileDao.refresh(currentTranscodingFile);
            } catch (Exception e) {
                Timber.e("progress:" + Log.getStackTraceString(e));
            }
            shouldSendTranscodeUpdateBroadcast = true;
        }

        @Override
        public void start(String videoInfo) {

        }
    }
}
